0

I want to apply multiple classes .active on item click and another class based on some condition. How can i do both? Below is the code which I have and only MyAnotherClass gets applied.

<li ng-class="(item.name == currentState && 'active' && isItemValid(item) && 'myAnotherClass' )" ng-repeat="item in menuItems">
        <a ui-sref="{{item.name}}"  ng-click="selectedItem(item)">{{item.name}}</a> 
</li>

2 Answers 2

2

With ng-class, you can separate the classes (and their respective rules (expressions)) using a comma separated listing.

Here is an example:

<li ng-class="{'active': isActive && !isDeleted, 'myAnotherClass': isValidOtherClass}"></li>

This technique should allow you to accomplish any combination of dynamically applied classes.

Documentation for ng-class is here.

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

Comments

1

Per the ngClass directive documentation, use an object literal with keys of the class names to apply and values of the boolean variables to indicate to add/remove the classes.

It appears that you can use expressions that resolve to booleans in place of a variable in v1.2.6. However, I haven't tested functions.

<li ng-class="{ active: item.name == currentClickState, myAnotherClass: isItemValid(item) }" ng-repeat="item in navigationMenuItems">
    <a ui-sref="{{item.name}}"  ng-click="selectedItem(item)">{{item.name}}</a> 
</li>

P.S. Have a look at Logical Operators. With && the myAnotherClass is only applied if every statements before it is truthy, and active will never be applied as that string is truthy and the next statement is tested. I'm guessing you were intending something like (item.name===currentClickState ? 'active' :'')+(isItemValid(item) ? 'myAnotherClass' :'') (That's a Conditional Operator)

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.