AngularJs event $stateChangeStart not firing

Issue

I’m trying to implement a route based security for users and the stateChangeStart doesn’t fire, this is my code :

app.run(['$rootScope', '$location', function($rootScope, $location) {
    $rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
      console.log('$stateChangeStart to '+toState.to+'- fired when the transition begins. toState,toParams : \n',toState, toParams);
   });

}]);

So whenever I change the route, and jump from one link/controller to another, nothing happens, however when I add a console log inside individual controllers I do see the console log statements.

What am I doing wrong here? How can I debug this, I’m not very experience person in angular

Update

I guess I’m using ngRoute and not ui-router

Is there something equivalent for ngRoute that I get the state change on a root scope. Migrating to ui-router seems a big change to do at this point for this purpose

Solution

Yes you have differents events from the $route provider : $routeChangeStart, $routeChangeSuccess, $routeChangeError

$rootScope.$on('$routeChangeStart', function(event, next, current) {
    // TODO
});

The doc : https://docs.angularjs.org/api/ngRoute/service/$route

Answered By – Damien

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.