Looking for an event before leaving a page


#1

Hello,

I am looking for an event that trigger when the user want to leave a page.

I tried this

$scope.$on('$locationChangeStart', function (event, next, current) {
  console.log(next);
  console.log(current);
});

But it trigger when i enter the page :
console.log(next) is the page related to $scope
console.log(current) is the page that i come from

$locationChangeEnd doesn’t exist…

Do you know what i need ?!

Thanks to community !


#2
$rootScope.$on("$routeChangeStart", function(args){})

$rootScope.$on("$routeChangeSuccess"....

$rootScope.$on("$routeChangeError"....

https://docs.angularjs.org/api/ngRoute/service/$route


#3

i put that in my controller :

$rootScope.$on("$routeChangeStart", function(args) {
  console.log(args);
});

but nothing is logged.

I forget to say that I use ‘ui.router’ for routing…

I’ll try that http://angular-ui.github.io/ui-router/site/#/api/ui.router.router.$urlRouter


#4

Ah. Different story then. Have you tried…

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ ... })

#5

Nice @andrewmcgivery it works fine like this :

$scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
  if( fromState.name == 'home' && event.currentScope.tabSelected == 'hangout' ) {
    Do something in factory..
  }
});

I changed $rootScope by $scope to get access to my scope.
I can now do something in factory when i leave my home page and also depending on condition in my currentScope.

Thanks for your help :smiley:


#6

Glad I could be of service. :slight_smile:


#7

You can also try this

$scope.$on('$destroy',function(){
            // do something
        });

#9

Helps a lot, thx for your help.


#10

Since ionic beta 14 you can listen to $ionicView events

$scope.$on('$ionicView.leave', function(){
  // do all kind of stuff
});