I\'m trying to block all ui-router state changes until I\'ve authenticated the user:
$rootScope.$on(\'$stateChangeStart\', function (event, next, toParams) {
I also had this issue. Below is the code to workaround, which inspired by angular-permission project.
The main concept is to add a flag($$finishAuthorize
) into state manually, and break the infinite loop by this flag. Another point we need to be aware is the {notify: false}
option of $state.go
, and broadcast "$stateChangeSuccess"
event manually.
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (toState.$$finishAuthorize) {
return;
}
if (!authenticated) {
event.preventDefault();
toState = angular.extend({'$$finishAuthorize': true}, toState);
// following $timeout is emulating a backend $http.get('/auth/') request
$timeout(function() {
authenticated = true;
$state.go(toState.name, toParams, {notify: false}).then(function() {
$rootScope.$broadcast('$stateChangeSuccess', toState, toParams, fromState, fromParams);
});
},1000)
}
);