Search code examples
angularjsng-class

Using a variable in ng-class AngularJS


I have 3 divs which will have a class "yellow" assigned according to a specific value using the following ng-class="{item.color : item.value}

This class yellow is also stored in a variable which is item.color

However I want to insert the class name through a variable by using ng-class="{item.color : item.value} but it's not working because item.color is not a valid expression. But if I use ng-class="item.color" (which gives me a different result I don't want) it works just fine.

You have more information in the following plunker:

https://plnkr.co/edit/unZDIWc6DvM4cLpALKSK?p=preview

Any suggestions?

Thank you


Solution

  • The following will highlight the div yellow if value is true if this is what you intend.

     ng-class="item.value && item.color"
    

    OR

     ng-class="item.value ? item.color : ''"