ng-show and ng-hide with jwt

北城余情 提交于 2019-12-11 13:44:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!