I'm trying to redirect an AngularJS app in the case that the requested state requires login. This is the method I've placed within the 'run' method on my angular app:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if(toState.data.requiresLogin && !User.isLoggedIn)
{
event.preventDefault();
$state.go('login');
}
});
Seems straightforward, but I'm getting this digest error. It appears to be triggered by the event.preventDefault() statement. I can't remove that of course...
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: $locationWatch; newVal: 7; oldVal: 6"],["fn: $locationWatch; newVal: 8; oldVal: 7"],["fn: $locationWatch; newVal: 9; oldVal: 8"],["fn: $locationWatch; newVal: 10; oldVal: 9"],["fn: $locationWatch; newVal: 11; oldVal: 10"]]
...
Any advice on how to refactor this to clear this error, or what the error even means?
There is a working example, how to redirect to login. Firstly there are 4 states defined - 2 of them require authentication, third is public (for anybody) and there is also login state:
and that would be the
$stateChangeStart
def, which always redirects tologin
- if required ... onlylogin
itslef andpublic
are available always/to anybodyCheck that all in action here