Ionic: How to override back button function?

风格不统一 提交于 2019-12-30 10:08:39

问题


I need to override the back button function for both buttons:

  • the back icon on top left corner of nav-bar
  • the hardware back button (for example in android)

but only for one specific view, not globally. How can i do that?


回答1:


This code is for android button, while the button on the navigation bar is a bit more simple:

Android button :

$ionicPlatform.registerBackButtonAction(function (event) {
  if($state.current.name=="home"){
    alert("button back");
  }
}, 100);

Ionic button :

You can edit your topic and see how you have defined your menus and your views?




回答2:


It is possible to override the back button functionality for both buttons from within your controller. Here is the code for that:

// 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();
});

Make sure to inject $rootScope into the controller.


For more details and a proper explanation, see my full answer at related question:

  • Ionic override all BACK button behaviour for specific controller


来源:https://stackoverflow.com/questions/31585320/ionic-how-to-override-back-button-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!