Check if value in array in angular template?

Anonymous picture Anonymous · Jan 14, 2014 · Viewed 78.3k times · Source

Is there any way to check if a value is in an array in an angular template? I'm looking to something like this:

<div ng-class="{'myClass':1 in [1,2,5]}">Yay</div>

Where myClass is applied if 1 is in the array.

Is this possible?

And as an aside, what templating engine exactly is used with Angularjs? Where can I find documentation for it? Whenever I try and search (even official docs), I only seem to turn up docs on directives or data binding.

Answer

KayakDave picture KayakDave · Jan 14, 2014

You can use indexOf() to test whether a value is in an array and then use it inside your ngClass like this (to conditionally add "newclass"):

<div ng-class="{'newclass':([1,2,5].indexOf(2) > -1)}">Yay</div>

Or more likely you'll want to test against an array on your scope:

<div ng-class="{'newclass':(tarray.indexOf(1) > -1)}">Yay</div>

Assuming, for instance, you have declared tarray in your controller:

$scope.tarray=[1,2,5];

demo

As far as a template engine, it's built in to Angular. So there's not really something separate to search for. But here's the top level template docs and there's some good video tutorials here that cover templates (for instance the first one is on data binding) as well as much more.