Why is $stateChangeStart triggering multiple times?

angular-ui-router, angularjs

Solution

Your controller is instantiated by ui-router every time you enter the state it is associated with. Therefore, your `$rootScope.$on` call will be adding a new listener to the `$stateChangeStart` event each time you enter that state.

If you only need to handle the event once per controller instance, you can save the deregister function that `$rootScope.$on` returns and execute it from within the listener callback.

var deregisterStateChangeStart = $rootScope.$on('$stateChangeStart', function (event) {
    // Do something here.

    deregisterStateChangeStart();
});

Problem

I am trying to use `$stateChangeStart` with ui router in a controller. It seems like everytime it's fired, the callback fires +1 times more than the last time. ``` $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ console.log('$stateChangeStart'); }); ``` For example, on first change start `console.log` will be fired once. second time `console.log` will be fired twice, etc etc. I know using `event.preventDefault()` will stop this behavior, but it'll also stop all behaviors and that's not a realistic solution to me. I do have a solution although I feel like there might be a more intelligent way to handle this: ``` var stateChangeStarted = false; $rootScope.$on('$stateChangeStart', function(event){ if(!stateChangeStarted) { stateChangeStarted = true; console.log('$stateChangeStart'); } }); ``` Does anyone have any idea why this is happening and what else I can do to prevent this?

Original source