Ionic: How to override back button function?

2020-03-24 08:00发布

问题:

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