Mega Man Mega Man - 8 months ago 38
AngularJS Question

Angular detect leaving a route.

I'm using Angular 1.5 and ui-router. I want to detect when a user

a route. I've currently got something like:

$scope.$on("$stateChangeSuccess", function () {
if (!$scope.flag) {

this doesn't quite work because when the user navigates to the this route,
is set to
and this function incorrectly fires. Is there an idiomatic way to fire a function when a user navigates away from a particular route, but not when they navigate to it?


I'd say use onExit hook of ui-router which you can specify on single state. But you can't access $scope inside it.

To deal with it, I'd say maintain service which will have shareable data. Change that shareable data from onExit hook of your desired state. Then you can access the same service inside your controller as well.

$stateProvider.state("contacts", {
  template: '<h1>Dummy Template</h1>',
  controller: 'myCotroller',
  onExit: function(sharableService){
    //... do something sharableService variable...