how to restore ionic backbutton after override? -

2019-09-07 07:21发布

问题:

Currently the backbutton override on a particular page is working on the particular Tab-SubTab (A) I am applying it to - on SubTabA, the back button takes me back to TabA, but the $scope.$on('$destroy...) doesn't seem be working. Because if from Tab-SubTab(A) and I navigate directly to another Tab-SubTab (C) page - the back button on Tab-SubTab (C) takes me directly back to TabA instead of back to TabC.

Furthermore, If I go back to TabC - it takes me directly into Tab-SubTabC (because thats where it last left off) and I can never get back into TabC.

Below is my controller for the particular page/Tab I am on:

  $scope.$on('$ionicView.beforeEnter', function(){
      // some none related stuff here.
  }) ;
  // custom back button to send user to master Rides tab no matter how many subviews they navigate to
  //
  //
  var doCustomBack = function() {
      $state.transitionTo('tab.rides');
  };
  // 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();
  });

I thought the $scope.$on('$destroy'...) would prevent that from happening, but obviously its not.

Visual of navigation:

Tab A (controller: tabA)
   -> Sub Tab A1 (controller: subTabA)  <- above backbutton overrides here
Tab B (controller: tabB)
   -> Sub Tab B1 (controller: subTabB)
Tab C (controller: tabC)
   -> Sub Tab C1 (controller: subTabC)
Tab D (controller: tabD)

Across top of my app is

HOME    TabA     TabB     TabC     TabD

If I got to TabA -> SubTabA, click back button, takes me back to TabA
If I got to TabA -> SubTabA, then go directly to TabC (from top of app) then to -> SubTabC, 
the back button on SubTabC takes me directly back to TabA content.

回答1:

The problem was $destroy was not triggering fast enough before the statechange. So moved to this:

  1. change: var oldSoftBack = $rootScope.$ionicGoBack to:

$rootScope.oldSoftBack = $rootScope.$ionicGoBack ;

  1. Instead of $scope.$on('$destroy'...) use this:

var backStateChangeWatcher = $rootScope.$on('$stateChangeStart', function () {
  if($rootScope.oldSoftBack){
    deregisterHardBack();
    deregisterSoftBack();
    // Un-register watcher
    backStateChangeWatcher();   
  }
}) ;