这是我在标题html中的登录表单:
<ul class="nav navbar-nav navbar-right" ng-controller="loginController">
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown" ng-show="$scope.loggedIn"><b>Logout</b></a>
<a href="" class="dropdown-toggle" data-toggle="dropdown" ng-show="!$scope.loggedIn"><b>Login</b> <span class="caret"></span></a>
</li>
</ul>
使用ui-router的Index.html:
<body>
<div ui-view="header"></div>
<div ui-view="content"></div>
<div ui-view="footer"></div>
</body>
在登录控制器中,我将布尔值设置为true:
$scope.loggedIn = AuthenticationService.isLogged;
$scope.loginForm = function (email, password) {
if (email !== undefined && password !== undefined) {
UserService.logIn(email, password).success(function (data) {
$localStorage.token = data.token;
console.log("stored token is: " + $localStorage.token);
if ($localStorage.token) {
$state.go('LoggedIn');
}
}).error(function(status, data){
console.log(status);
console.log(data);
});
}
}
UserService:
myApp.factory('UserService', function ($http, $localStorage, AuthenticationService) {
return {
logIn: function (email, password) {
return $http.post('rs/loginResource/login', {email: email, password: password});
AuthenticationService.isLogged = true;
},
logOut: function () {
if (AuthenticationService.isLogged) {
AuthenticationService.isLogged = false;
delete $localStorage.token;
}
}
};
});
身份验证服务:
myApp.factory('AuthenticationService', function() {
var auth = {
isLogged: false
};
return auth;
});
登录后,我将标志设置为true。但按钮名称不会更改为注销。我正在使用ui-router来改变状态。
答案 0 :(得分:2)
您永远不会设置$scope.isLogged
,只需更改服务价值即可。我认为您应该在AuthenticationService
内设置UserService
并在控制器中进行检查
logIn: function (email, password) {
return $http.post('rs/loginResource/login', {email: email, password: password})
.then(function(response){
//Some validation here to make sure that the user was successfully logged in
AuthenticationService.isLogged = true;
return response;
}).catch(function(error){/*error handling here */});
}
....
$scope.AuthenticationService = AuthenticationService;
$scope.loginForm = function (email, password) {
//delete this AuthenticationService.isLogged = true;
UserService.logIn(email, password).then(function(response){
var data = response.data;
$localStorage.token = data.token;
...
<a href="" class="dropdown-toggle" data-toggle="dropdown" ng-show="$scope.AuthenticationService.isLogged"><b>Logout</b></a>
<a href="" class="dropdown-toggle" data-toggle="dropdown" ng-show="!$scope.AuthenticationService.isLogged"><b>Login</b> <span class="caret"></span></a>