Tomarto Tomarto - 1 year ago 81
AngularJS Question

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
to know where am I going to be redirected and from where?

Answer Source

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:

You might also want to check $route documentation ($route) to see other events emited by the $route service.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download