问题
I'm managing authentication with JWT. I'm trying to use ng-hide and ng-show to show/hide login and logout buttons in my nav. It's not working. The token is being stored, but I'm unable to get the show/hide to work.
Service:
angular.module('psJwtApp')
.factory('authToken', function ($window) {
var storage = $window.localStorage;
var cachedToken;
var userToken = 'userToken';
var isAuthenticated = false;
var authToken = {
setToken: function (token) {
cachedToken = token;
storage.setItem(userToken, token);
isAuthenticated = true;
},
getToken: function () {
if(!cachedToken)
cachedToken = storage.getItem(userToken);
return cachedToken;
},
isAuthenticated: function () {
return !!authToken.getToken();
},
removeToken: function () {
cachedToken = null;
storage.removeItem(userToken);
isAuthenticated = false;
}
};
return authToken;
});
Controller:
angular.module('psJwtApp')
.controller('HeaderCtrl', function ($scope, authToken) {
$scope.isAuthenticated = authToken.isAuthenticated();
});
html:
<div ng-controller="HeaderCtrl" class="header">
<ul class="nav nav-pills pull-right">
<li ui-sref-active="active">
<a ui-sref="main">Home</a>
</li>
<li ui-sref-active="active">
<a ui-sref="jobs">Jobs</a>
</li>
<li ng-hide="isAuthenticated()" ui-sref-active="active">
<a ui-sref="login">Log In</a>
</li>
<li ng-show="isAuthenticated()" ui-sref-active="active">
<a ui-sref="logout">Logout</a>
</li>
</ul>
<h3 class="text-muted">psJwt</h3>
</div>
回答1:
Have you checked the type of $scope.isAuthenticated? i suspect that it has resolved to a boolean, not a function. Update your html to check against the boolean value.
<li ng-show="!isAuthenticated" ui-sref-active="active">
<a ui-sref="login">Log In</a>
</li>
<li ng-show="isAuthenticated" ui-sref-active="active">
<a ui-sref="logout">Logout</a>
</li>
来源:https://stackoverflow.com/questions/27466044/ng-show-and-ng-hide-with-jwt