I\'m using ui.router
for routing in my Angular app. There is a typical login scenario, where I\'m redirecting a user to the login url if he\'s not logged in. Wi
I used something similar to this:
MyApp.run(['$rootScope', '$state', function ($rootScope, $state) {
// The event
$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
// Is user already logged in?
var isUserLoggedIn = $rootScope.isUserLoggedIn();
if (isUserLoggedIn) {
// don't let user visit login state, he's already logged in.
$state.go('home');
// preventDefault as described in @radim's answer
e.preventDefault();
} else if (toState.name === "login") {
// user is not logged in and is not going to login state right now, send him there first.
$state.go('login');
// preventDefault as described in @radim's answer
e.preventDefault();
}
});
}]);