Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value in array in angular template?

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.

like image 730
Anonymous Avatar asked Jan 14 '14 20:01

Anonymous


2 Answers

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.

like image 88
KayakDave Avatar answered Sep 18 '22 14:09

KayakDave


You can create a filter to check this. Something like:

app.filter('inArray', function() {     return function(array, value) {         return array.indexOf(value) !== -1;     }; }); 

Then you can use this in your template with:

<div ng-class="{'newclass': tarray | inArray : 1}">Yay</div> 

The advantage to this is that it makes your template more readable.

like image 20
Martin Avatar answered Sep 20 '22 14:09

Martin