Ila
Ila

Reputation: 3538

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

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 ?

Upvotes: 36

Views: 51840

Answers (2)

BusyBetty
BusyBetty

Reputation: 229

You can also do this short hand:

    ng-class="category==16 ? 'icon-pfeil_unten' : 'icon-pfeil-oben'"

Upvotes: 22

tymeJV
tymeJV

Reputation: 104795

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

Upvotes: 62

Related Questions