Opposite of $routeChangeSuccess in AngularJS
Asked Answered
Z

1

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?

Zennas answered 7/9, 2012 at 15:34 Comment(0)
R
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.

Rozier answered 7/9, 2012 at 17:38 Comment(2)
Thank you very much! this is just what I was searching for!Zennas
Thanks. But the first argument is event actually.Montanez

© 2022 - 2024 — McMap. All rights reserved.