Search code examples
javascriptangularjsng-class

How to check if something is in array from ng-class


I want to do something like:

var list = [1,2,3,4,5]
if(2 in list){
  return true
}

from a ng-class, so I tried:

ng-class="this.id in list ? 'class-1' : 'class-2' ">

But doesn't worked, throws an error

Syntax Error: Token 'in' is an unexpected token at ...

Solution

  • For arrays you'd use indexOf, not in, which is for objects

    if ( list.indexOf(this.id) !== -1 ) { ... }
    

    so

    ng-class="{'class-1' : list.indexOf(this.id) !== -1, 'class-2' : list.indexOf(this.id) === -1}"