-->

NG-Show if array contains a certain value and not

2019-04-16 14:47发布

问题:

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.