Reputation: 107
i'm learnign angular.js and ui-router. So I'm triying to understand: 1. How to do two different actions in one state depending user is logged in or no. 2. In several sates redirect to home pageif user is Not Logged in
Here is example: There is a servise "Atuhentication" that countains authentiated user. But I can't load it to module.config() it hrows an error.
$stateProvider
.state('home', {
// if user is logged in go to state "chat"
// else go to state "welcome"
})
.state('chat', function(){
// if user is not logged in redirect to home page
})
I tried to make it in state's controllers, but it is dirty way, because it loads template & controller and then check if user logged in and redirects if not.
So dear friends, please show the right direction to move
Upvotes: 1
Views: 522
Reputation: 25797
You can always hook & prevent the state change using $stateChangeStart
event which is being broadcasted when a state is changed. You can add this event listener either in any top level controller which is available through out the app (like a controller added to body
tag) or you can add this event listener code in any service using $rootScope
like below:
var protectedStates = ['home', 'chat'];
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
// See if state being transitioned needs to be access checked
if (protectedStates.indexOf(toState.name) > -1) {
if (!userLoggedIn) {
// Prevent the current state from being changed
event.preventDefault();
$state.go('home'); // go to home page or login page.
}
}
});
For more reference: http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state
Hope this helps!
Thanks,
SA
Upvotes: 1