I'm using angular1.4,ui.router0.2.15. Trying to redirect to login state in $stateChangeStart. Here's the logic:
$rootScope.on('$stateChangeStart', function(){
if(!isLoggedIn && toState.name !== 'login') {
console.log('go to login');
e.preventDefault();
$state.go('login');
} else if (isLoggedIn && toState.name === 'login') {
console.log('go to home');
e.preventDefault();
$state.go('home');
} else {
console.log('no change');
}
});
I thought the execution will be like:
event1: from:'', to:'home', 'go to login'
event2: from:'', to:'login', 'no change'
...then proceed
But in fact it is:
event1: from:'', to:'home', 'go to login'
event2: from:'', to:'login', 'no change'
event3: from:'', to:'home', 'go to login'
event4: from:'', to:'login', 'no change',
event5: from:'', to:'home', 'go to login',
...the dead loop continues until max digest loop
I spotted that event3 is trigger in angular-ui-router.js function registerState:
// Register the state in the global state list and with $urlRouter if necessary.
if (!state[abstractKey] && state.url) {
$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
$state.transitionTo(state, $match, { inherit: true, location: false });
}
}]);
}
But I lost track of the problem since it's too complicated.
Why event3 fired??? And if I wanted my redirection should I register my own event like $myStateChangeStart???