Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 8 down vote accepted

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.

share|improve this answer
    
Thanks, exactly what I was looking for - didn't realize quite how much JS I could use in the templates. –  Anonymous Jan 14 at 21:03
    
This doesn't work for object inside arrays though –  Mauro De Giorgi Feb 28 at 23:24

Try this:

ng-class="{'myClass':  !!~[1,2,5].indexOf(1)}"

if the value isn't in array you get 0 therefore with !! you get false

share|improve this answer
    
indexOf returns -1 when the item is not in the array –  Gruff Bunny Jan 14 at 21:12
    
@Gruff Bunny ~[1,2,5].indexOf(3) with the bit operations you get 0 –  Whisher Jan 14 at 21:13
    
Oops - didn't see the not there - i do apologise –  Gruff Bunny Jan 14 at 21:16
    
Great idea- but unfortunately bitwise operators are not supported in Angular expressions: github.com/angular/angular.js/issues/2838 –  KayakDave Jan 14 at 21:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.