简体   繁体   English

Angular JS-如何在对象数组中查找字符串?

[英]Angular JS - How to find string in array with objects?

I am new to Angular JS and have a limited background in JavaScript, so sorry if I am not explaining this right. 我是Angular JS的新手,并且对JavaScript的背景知识有限,所以如果我不解释此权利,对不起。

I am looking to show an image based upon a value in an array that contains objects. 我想要显示基于包含对象的数组中的值的图像。 Here is what I have, which works: 这是我所拥有的,可以正常工作:

<img ng-show="user.Groups[0].Name=='Consumers'" src="images/home.jpg" />

The problem that I am running into is that [0] could also be [1], [2], [3], etc. What can I use to ensure it checks all indexes? 我遇到的问题是[0]也可能是[1],[2],[3]等。我可以使用什么来确保它检查所有索引?

Here's one way. 这是一种方法。

Put this in your controller: 将其放在您的控制器中:

$scope.objArrayContains = function(arr, keyName, val) {
    return arr.map(function(a) { return a[keyName]; }).indexOf(val) !== -1;
};

Then your HTML can be like this: 然后,您的HTML可以像这样:

<img ng-show="objArrayContains(user.Groups, 'Name', 'Consumers')" src="images/home.jpg" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM