NG-Show if array contains a certain value and not another

非 Y 不嫁゛ 提交于 2019-12-06 13:07:55

问题


I have an 3 user rights - Admin, User, and Editor. The way this is setup is:

If you are an Admin the return is roles: ["Admin", "User", "Editor"]

If you are an User the return is roles: ["User"]

If you are an Editor the return is roles: ["User", "Editor"]

Now what I have now is ng-show="object.roles.length < 2" = User and etc. for the other two.

I am sure there is a better/smarter way to do this or maybe it is easier to do it this way. I am just not sure how to go about it differently. Thanks for the suggestions.


回答1:


That is not a good idea. You are managing your app's UI by counting an array length. What if this changes? I would suggest to verify always if the role needed is owned. For example ng-show="hasRole('User')"

$scope.hasRole = function(role){
     var indexOfRole = $scope.roles.indexOf(role); // or whatever your object is instead of $scope.roles
     if (indexOfRole === -1)
          return false;
     else
          return true;
}



回答2:


<div ng-show="roles.indexOf('Admin') >= 0"

Or, to be cleaner, delegate to a scope function:

<div ng-show="hasRole('Admin')"

and

$scope.hasRole = function(roleName) {
    return roles.indexOf(roleName) >= 0;
}



回答3:


This worked for me:

<div class="lil" ng-show="role.rileName.includes('someother') == 0 && role.rileName.includes('Admin')">
    <a class="{{role.rileName}}" href="javascript:void(0);" title="{{role.rileName}}" ng-controller="sampleRequestController" ng-click="addSamples(role.rileID,items.CanOrder);">{{role.rileName}}</a>
</li>

It will not show if == 0, otherwise it will.



来源:https://stackoverflow.com/questions/33047519/ng-show-if-array-contains-a-certain-value-and-not-another

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