Joe82 Joe82 - 3 months ago 9
AngularJS Question

AngularJS - ng-if if there is a specific value in array

I would like to trigger

ngIf
when there is a specific value in an array inside the scope.

So I have this on my scope:

var orders = [{
"order_no": 1,
"color": ["blue", "pink", "red"]
}, {
"order_no": 2,
"color": ["yellow", "blue", "white"]
}];


I would like to have an
ngIf
that shows one element if, for example, yellow is present in one of the color arrays (given that I would not know the data scope in advance, but knowing the structure in advance).

The only way I have found to do that would be when knowing the structure of the scope in advance, so fx
ng-if="orders[1].color[0] === 'yellow'"


Thanks!

Answer

You can call the indexOf method of the color array inside your HTML template. This way, you don't need to pollute the $scope with additional methods.

Here's how: ng-if="order.color.indexOf('pink') !== -1"

Note: don't forget that expressions in AngularJS are different. One key factor to remember is that they are forgiving.

Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In Angular, expression evaluation is forgiving to undefined and null.

This means that something like myCtrl.foo.bar.wa.la will evaluate to undefined which doesn't trigger ngIf. You can read more about it here.