我已经创建了一个例子 http://plnkr.co/edit/3kImqU?p=preview,使用默认页面和 auth/unauth 用户。可以看到类似的问题here https://stackoverflow.com/a/24725180/1679310
首先,这将是听众:
app.run(function ($rootScope, $state, $location, Auth) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState) {
var shouldLogin = toState.data !== undefined
&& toState.data.requireLogin
&& !Auth.isLoggedIn ;
// NOT authenticated - wants any private stuff
if(shouldLogin)
{
$state.go('login');
event.preventDefault();
return;
}
// authenticated (previously) comming not to root main
if(Auth.isLoggedIn)
{
var shouldGoToMain = fromState.name === ""
&& toState.name !== "main" ;
if (shouldGoToMain)
{
$state.go('main');
event.preventDefault();
}
return;
}
// UNauthenticated (previously) comming not to root public
var shouldGoToPublic = fromState.name === ""
&& toState.name !== "public"
&& toState.name !== "login" ;
if(shouldGoToPublic)
{
$state.go('public');console.log('p')
event.preventDefault();
}
// unmanaged
});
});
怎么了?
- 我们检查用户是否登录。如果没有,但需要访问非公开内容...我们重定向到登录
- 用户已登录,但没有直接进入主页面...我们将他转移
- 用户未登录,但不会公开...我们重定向
- 否则……就这样吧
以下是状态:
$stateProvider
// available for anybody
.state('public',{
url : '/public',
template : '<div>public</div>',
})
// just for authenticated
.state('main',{
url : '/main',
template : '<div>main for authenticated</div>',
data : {requireLogin : true },
})
// just for authenticated
.state('other',{
url : '/other',
template : '<div>other for authenticated</div>',
data : {requireLogin : true },
})
// the log-on screen
.state('login',{
url : '/login',
templateUrl : 'tpl.login.html',
controller : 'LoginCtrl',
})
Check 笨蛋在这里 http://plnkr.co/edit/3kImqU?p=preview or here https://stackoverflow.com/a/24725180/1679310