AngularJS基于角色的导航

AngularJS Role Based Navigation

本文关键字:导航 角色 于角色 AngularJS      更新时间:2023-09-26

我正在使用angular构建一个小型web应用程序。我正在尝试设置基于角色的导航。似乎在页面加载时没有调用isAdmin函数,因为我只能看到foo锚标记

HTML

<body ng-controller='AccountController'>
    <nav class="navbar navbar-default">
      <ul>
          <li><a href='google.com'>foo</a></li>
          <li ng-if="isAdmin()"><a href='google.com'>bar</a></li>
      </ul>
    </nav>
</body>

账户管理员

var app = angular.module('appControllers', []);
app.controller = angular.controller('AccountController', ['$scope', 
function($scope, $http) {
    $scope.isAdmin = function() {
        return true; //Just as a test to make sure it works
    }
}]);

理想情况下,这将击中一个将返回管理员状态的web服务,但目前我想让它发挥作用。

感谢您提前提供的帮助,

Andres

在您的示例中,您需要移除大括号才能使其工作。但我通常使用自定义指令使其工作。示例:

<div class="somediv" show-for-role="ROLE_A,ROLE_B"></div> 

如果你的用户有这些角色,你可以管理它

appModule.directive('manageAccess', ['someState', function (appState) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var user = someState.currentUser;
      scope.$watch(someState.watchCurrentUser, function(n,o){
         if (n === o){
           return;
         }
        hideShow(element,attrs,n);
      });
      hideShow(element,attrs,user);
    }
  }
var hideShow = function(element,attrs,user){
element.hide();
if (user) {
  var role = attrs.showForRole;
  if (role){
    role.split(',').forEach(function(it){
      if (it == user.role){
        element.show();
      }
    })
  }
}};

尝试删除'isAdmin'之后的额外'[()',如下所示:

function($scope, $http) {
    $scope.isAdmin = function() {
        return true; //Just as a test to make sure it works
    }
}

希望它能帮助。。。