Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS, using ng-class to assign a class if variable = something

Tags:

angularjs

I'm trying to assign a different class to an icon if its category is selected. I want to add class ìcon-pfeil_unten` if variable category == a number. I am trying with:

<i class="icon-pfeil_oben" ng-class="{'icon-pfeil_unten': category.16}"></i> 

Where 16 is the category's ID. If category == 16, nothing happens. I guess I am writing the expression wrong. What's the correct way to test the value of a variable using ng-class ?

like image 741
Ila Avatar asked Nov 01 '13 13:11

Ila


People also ask

How do you apply ngClass based on condition?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

Can I use ngClass and class?

You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

Can we use NGIF and ngClass together?

javascript - ng-if and ng-class-even/odd doesn't work well together and won't get expected outout - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


1 Answers

You can do:

ng-class="{true: 'icon-pfeil_unten', false: 'icon-pfeil-oben'}[category == 16]" 

So basically, if category == 16 evals to true, add class icon-pfeil_unten

like image 165
tymeJV Avatar answered Sep 19 '22 06:09

tymeJV