Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $stateChangeStart triggering multiple times?

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?

like image 446
muudless Avatar asked Nov 22 '14 00:11

muudless


Video Answer


1 Answers

Clear out the listeners for stateChangeStart at the beginning of your controller.

$rootScope.$$listeners.$stateChangeStart = [];
like image 60
duyn9uyen Avatar answered Sep 20 '22 08:09

duyn9uyen