36

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 ?

0

2 Answers 2

62

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! Is it possible to toggle between two classes using a statement like this, e.g "if category == 16, add class icon-pfeil_unten, otherwise add class icon-pfeil_oben", or is there a better way to do that?
@Ali -- Yeah, I edited the answer, I believe that should work.
Worked like a charm, once I removed the initial class="" tag. Doesn't work if I leave that in. So the complete working element is: <i aria-hidden="true" ng-class="{true: 'icon-pfeil_unten', false: 'icon-pfeil_oben'}[category == 16]"></i>
@tymeJV Just curious, What if more than 1 class is to be made true (I mean activated) on the condition? What is the syntax for doing that? Thanks.
@Dravidian - I assume just add another class for the true condition, IE: ng-class="{true: 'icon-pfeil_unten and_another_class' ..
|
22

You can also do this short hand:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.