admin管理员组

文章数量:1352198

I have a application using Ruby on Rails (Devise/CanCan for Authentication/Roles) and a AngularJS client.

I have 3 roles - each with different navigation menus. I'd rather not have 3 different views with different navigation bars- is there a way I can show/hide navigation elements based on which user is loaded?

Anyone familiar with this or have any good ideas? I did some hunting but came up with little to no success... Anything helps!

I have a application using Ruby on Rails (Devise/CanCan for Authentication/Roles) and a AngularJS client.

I have 3 roles - each with different navigation menus. I'd rather not have 3 different views with different navigation bars- is there a way I can show/hide navigation elements based on which user is loaded?

Anyone familiar with this or have any good ideas? I did some hunting but came up with little to no success... Anything helps!

Share Improve this question asked Feb 4, 2014 at 18:33 OHopeOHope 6281 gold badge10 silver badges18 bronze badges 1
  • ng-show – snaplemouton Commented Feb 4, 2014 at 18:44
Add a ment  | 

2 Answers 2

Reset to default 11

I know you already marked an answer but I wanted to point out a nuance related to performance.

Depending on the size of your menu and HTML you might want to go beyond ng-show to use ng-if. The problem with ng-show is that all of the nodes are piled, even the ones the user will never use. For example, a Manager may never use the Admin or User nodes but they are still parsed and piled.

If you use ng-if you can avoid that and only render/pile the fragments when the condition is true. Since you are always going to use the same controller, you wouldn't have to repeat it:

<div ng-controller="AccountController"> 
<div ng-if="IsAdmin()">...admin nav...</div>
<div ng-if="IsUser()">...user nav...</div>
</div>

We are on a massive Angular application and small changes like this reap major performance benefits. When the "if" expression fails, the element is removed from the DOM and never piled, vs. ng-show while will still pile the element and simply hide it.

You can use the ng-show tag.

You will do something like this:

<div ng-show="IsAdmin()" ng-controller="AccountController" >...admin nav...</div>
<div ng-show="IsUser()" ng-controller="AccountController" >...user nav...</div>
<div ng-show="IsManager()" ng-controller="AccountController" >...manager nav...</div>

..Controller

$scope.IsAdmin = function(){
    return $scope.UserRole == "Admin";
}

$scope.IsUser = function(){
    return $scope.UserRole == "StandardUser";
}

$scope.IsManager = function(){
    return $scope.UserRole == "Manager";
}

In your controller you determine some logic to show each nav based off of the role then return true/false.

本文标签: javascriptAngularJSRole Based NavigationStack Overflow