Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top