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

13,445

Solution 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;
}

Solution 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;
}
Share:
13,445
RooksStrife
Author by

RooksStrife

Updated on June 26, 2022

Comments

  • RooksStrife
    RooksStrife almost 2 years

    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.

  • Ignacio Villaverde
    Ignacio Villaverde over 8 years
    I have just seen your answer, we suggested almost the same way.