简体   繁体   中英

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.

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?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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