可以覆盖控制器中的两个按钮,而无需更改 HTML 代码。
总结一下:
-
软导航栏按钮 - 覆盖
$rootScope.$ionicGoBack()
-
Android 硬按钮 - 使用
$ionicPlatform.registerBackButtonAction()
下面有详细解释。
覆盖软导航栏 BACK 按钮的解决方案来自于了解按下该按钮时 Ionic 的作用。
从Ionic docs for ion-nav-back-button,我们已经知道:
点击/点击按钮会自动设置为$ionicGoBack()。
在 ionic.bundle.js 中搜索源代码会发现这是如何声明的:
$rootScope.$ionicGoBack = function(backCount) {
$ionicHistory.goBack(backCount);
};
在您自己的控制器中覆盖它很简单。确保将$rootScope 传递到控制器中,然后只修改上面的代码。获取指向原始函数的指针是个好主意,这样您就可以在需要时恢复它,或者在完成自定义处理后调用它。
// grab pointer to original function
var oldSoftBack = $rootScope.$ionicGoBack;
// override default behaviour
$rootScope.$ionicGoBack = function() {
// do something interesting here
// uncomment below line to call old function when finished
// oldSoftBack();
};
覆盖 Android 硬件 BACK 按钮的解决方案,仅适用于一个控制器,来自 registerBackButtonAction() 函数的返回值,该函数会取消注册覆盖。
在$scope.$on('$destroy'... 处理程序中调用该注销方法。
var doCustomBack= function() {
// do something interesting here
};
// registerBackButtonAction() returns a function which can be used to deregister it
var deregisterHardBack= $ionicPlatform.registerBackButtonAction(
doCustomBack, 101
);
$scope.$on('$destroy', function() {
deregisterHardBack();
});
更多细节在这里:
完整的解决方案需要以下内容:
- 覆盖软导航栏 BACK 按钮
- 覆盖 Android 硬返回按钮
- 范围将是单个控制器
- 恢复默认行为
以下代码说明了如何做到这一点:
// run this function when either hard or soft back button is pressed
var doCustomBack = function() {
console.log("custom BACK");
};
// override soft back
// framework calls $rootScope.$ionicGoBack when soft back button is pressed
var oldSoftBack = $rootScope.$ionicGoBack;
$rootScope.$ionicGoBack = function() {
doCustomBack();
};
var deregisterSoftBack = function() {
$rootScope.$ionicGoBack = oldSoftBack;
};
// override hard back
// registerBackButtonAction() returns a function which can be used to deregister it
var deregisterHardBack = $ionicPlatform.registerBackButtonAction(
doCustomBack, 101
);
// cancel custom back behaviour
$scope.$on('$destroy', function() {
deregisterHardBack();
deregisterSoftBack();
});
这个问题已经在 Ionic 论坛和问题页面上讨论过: