47

Is there any way to check if a value is in an array in an AngularJS 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.

3 Answers 3

84

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, exactly what I was looking for - didn't realize quite how much JS I could use in the templates.
Can I use findIndex here? like if I do have an array $scope.tarray=[{1},{2},{5}]; then how would I have to write syntax?
15

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.

2 Comments

Nice solution, but I needed to add parenthesis around the filter expression to avoid an angular syntax error. <div ng-class="{'newclass': (tarray | inArray : 1)}">Yay</div>
You could add the verification if array is an Array object (it might not always be an array, especially on initialization): return Array.isArray(array) && array.indexOf(value) !== -1;.
7

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

4 Comments

indexOf returns -1 when the item is not in the array
@Gruff Bunny ~[1,2,5].indexOf(3) with the bit operations you get 0
Oops - didn't see the not there - i do apologise
Great idea- but unfortunately bitwise operators are not supported in Angular expressions: github.com/angular/angular.js/issues/2838

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.