StateChangeStart runs multiple times

I am trying to use $stateChangeStart with a ui router in the controller. It seems that every time it starts, the callback is triggered +1 times more than last time.

 $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ console.log('$stateChangeStart'); }); 

For example, the first time you start, change start console.log will be launched once. the second time console.log will be run twice, etc. etc.

I know that using event.preventDefault() will stop this behavior, but it will also stop all behavior and will not be a realistic solution for me.

I have a solution, although I feel that there may be a more reasonable way to handle this:

 var stateChangeStarted = false; $rootScope.$on('$stateChangeStart', function(event){ if(!stateChangeStarted) { stateChangeStarted = true; console.log('$stateChangeStart'); } }); 

Does anyone know why this is happening, and what else can I do to prevent this?

+8
angularjs
source share
2 answers

Your controller is created using ui-router every time you enter the state with which it is associated. Therefore, your call to $rootScope.$on will add a new listener to the $stateChangeStart event each time you enter this state.

If you need to process the event only once per controller instance, you can save the registration function returned by $rootScope.$on and execute it from the listener callback.

 var deregisterStateChangeStart = $rootScope.$on('$stateChangeStart', function (event) { // Do something here. deregisterStateChangeStart(); }); 
+15
source share

Clear listeners for stateChangeStart at the beginning of your controller.

 $rootScope.$$listeners.$stateChangeStart = []; 
+4
source share

All Articles