3

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!

Cosmin Ababei
  • 7,003
  • 2
  • 20
  • 34
Joe82
  • 1,357
  • 2
  • 24
  • 40

2 Answers2

16

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.

Community
  • 1
  • 1
Cosmin Ababei
  • 7,003
  • 2
  • 20
  • 34
  • I will mark this as correct as the answer is more detailed, and having it in the html seems more straightforward to me. Thanks! – Joe82 Aug 21 '16 at 18:06
2

You could do this as a function expression

ng-if="hasYellow()"

$scope.hasYellow = () => $scope.orders.some(
  order => order.color.indexOf("yellow") > -1
);

Depending on the size of orders and how often it changes, it may be more efficient to just have a hasYellow property and update that when orders is changed.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405