NG-显示数组是否包含某个值,而不包含另一个值 [英] NG-Show if array contains a certain value and not another
问题描述
我拥有3个用户权限-管理员,用户和编辑者.设置方法是:
I have an 3 user rights - Admin, User, and Editor. The way this is setup is:
如果您是Admin
,则返回值为roles: ["Admin", "User", "Editor"]
If you are an Admin
the return is roles: ["Admin", "User", "Editor"]
如果您是User
,则返回值为roles: ["User"]
If you are an User
the return is roles: ["User"]
如果您是Editor
,则返回值为roles: ["User", "Editor"]
If you are an Editor
the return is roles: ["User", "Editor"]
现在我所拥有的是另外两个的ng-show="object.roles.length < 2" = User
等.
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.
推荐答案
那不是一个好主意.您正在通过计算数组长度来管理应用程序的UI.如果这改变了怎么办?我建议始终验证是否拥有所需的角色.例如ng-show="hasRole('User')"
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;
}
这篇关于NG-显示数组是否包含某个值,而不包含另一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!