我希望能够覆盖导航栏上的 BACK 按钮和硬件按钮。
我希望此覆盖适用于一个特定的 Controller ,而不适用于其余的 Controller 。
(使用 ionic v1.0.0 铀 unicorn )
我的原因是我有一个项目 list 。单击列表会打开一个详细信息页面,其中包含 3 个选项卡。每个选项卡共享相同的 Controller 。
但是,在任何这些选项卡上按 BACK 必须返回主列表。这就是它在 native 设备上的工作方式,所以这就是我希望它在我的混合应用程序上工作的方式。
许多在线提供的解决方案似乎适用于较旧的 Beta 版本,或适用于 Controller 之外的注册。
使用 Controller 内的 Android 硬件按钮的常见解决方案是:
$ionicPlatform.registerBackButtonAction(function (event) {
if($state.current.name=="home"){
alert("button back");
}
}, 100);
然而,这似乎不适用于软导航栏按钮,它适用于所有 Controller ,而不仅仅是一个。
最佳答案
可以覆盖 Controller 中的两个按钮 ,对 HTML 代码没有任何改动。
总结一下:
$rootScope.$ionicGoBack()
$ionicPlatform.registerBackButtonAction()
下面详细解释。
的解决方案覆盖软导航栏后退按钮 来自了解按下该按钮时 Ionic 的作用。
来自 Ionic docs for
ion-nav-back-button
,我们已经知道:the button is automatically set to
$ionicGoBack()
on click/tap.
在 ionic.bundle.js 中搜索源代码揭示了它是如何声明的:
$rootScope.$ionicGoBack = function(backCount) {
$ionicHistory.goBack(backCount);
};
在您自己的 Controller 中覆盖它很简单。确保您通过
$rootScope
进入 Controller ,只需修改上面的代码。获取指向原始函数的指针是个好主意,这样您就可以在需要时恢复它,或者在完成自定义处理后调用它。// 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 硬件后退按钮 ,仅针对一个 Controller ,来自
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();
});
更多细节在这里:
完整的解决方案需要以下内容:
以下代码说明了如何做到这一点:
// 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 论坛和问题页面上讨论过:
关于ionic-framework - ionic 覆盖特定 Controller 的所有后退按钮行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32231737/