Event capture "back" button ionic


#1

Hello community, I need to know how to capture the event of ion-nav button-back-button! if anyone knows how I can do it, I would appreciate it !!


#2

You could catch a generic navigation event, but there’s no specific event for the back button.

  $scope.$on("$ionicView.leave", function(){
    console.log("leaving");
  })

#3

Hello @mhartington that event and what I have captured, but I need before you return, ask a question, I need something like that friend!

$scope.$on("$ionicView.leave", function(event){
event.stopPropagation();
$ionicPopup.show({
     title: 'View',
     subTitle: '',
     content: '¿Are you sure you back?',
     buttons: [
       { text: 'No',
        onTap: function(e){
          
        }
       },
       {
         text: 'Yes',
         type: 'button-positive',
         onTap: function(e) {
              $ionicHistory.goBack();
         }
       },
     ]
    })
})

#4

Also try the following:

$scope.$on('$ionicView.beforeLeave', function(event){
alert("Before Leaving");
$ionicPopup.show({
   title: 'View',
   subTitle: '',
   content: '¿Esta seguro de no publicar este view?',
   buttons: [
     { text: 'No',
      onTap: function(e){
        
      }
     },
     {
       text: 'Si',
       type: 'button-positive',
       onTap: function(e) {
            $ionicHistory.goBack();
       }
     },
   ]
  })
 });

But the alert is sent well in view corresponding. But ionicPopup the $ionicHistory.goBack()runs and then the popup is launched. Why is that?


#5

You could override the ng-click of the ionNavBackButton:

<ion-nav-bar ng-controller="MyCtrl">
  <ion-nav-back-button class="button-clear"
    ng-click="myGoBack()">
    <i class="ion-arrow-left-c"></i> Back
  </ion-nav-back-button>
</ion-nav-bar>

JS:

function MyCtrl($scope, $ionicHistory) {
  $scope.myGoBack = function() {
    // Code to show popup and then go back
    $ionicHistory.goBack();
  };
}

Note: you can put this on one view if you only want it to display on a specific view: Codepen with this added to page 2.