9

I was just wondering if there is a way to know if someone is changing the route of the URL.

As an example, I have something like this in my html:

<a ng-href="#/somewhere">To somewhere</a>

and I was using this:

$scope.$on('$routeChangeSuccess', function (scope, next, current) {
    //Some code
})

However, I just realized that I need to run this code before changing the URL. Is there a way to to this and also to have the same next and current to know where am I going to be redirected and from where?

rockingskier
  • 9,066
  • 3
  • 40
  • 49
Tomarto
  • 2,755
  • 6
  • 27
  • 37

1 Answers1

24

There is the $routeChangeStart event that gets fired before route change. It support both next and current parameters, exactly like you would expect. So, to cover your use-case you could write:

$scope.$on('$routeChangeStart', function(scope, next, current){
        console.log('Changing from '+angular.toJson(current)+' to '+angular.toJson(next));
});

Here is the complete jsFiddle illustrating this in action: http://jsfiddle.net/pkozlowski_opensource/9MnE9/

You might also want to check $route documentation (https://docs.angularjs.org/api/ngRoute/service/$route) to see other events emited by the $route service.

Sam
  • 4,994
  • 4
  • 30
  • 37
pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286