Ionic: How to override back button function?

前端 未结 2 1775
情歌与酒
情歌与酒 2021-01-14 02:07

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 and
相关标签:
2条回答
  • 2021-01-14 02:33

    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
    0 讨论(0)
  • 2021-01-14 02:34

    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?

    0 讨论(0)
提交回复
热议问题