Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of $routeChangeSuccess in AngularJS

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?

like image 599
Tomarto Avatar asked Sep 07 '12 15:09

Tomarto


1 Answers

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.

like image 174
pkozlowski.opensource Avatar answered Oct 10 '22 23:10

pkozlowski.opensource