What is the best way to conditionally apply a class?

后端 未结 22 2598
感动是毒
感动是毒 2020-11-22 09:12

Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex.

22条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 09:31

    ng-class supports an expression that must evaluate to either

    1. A string of space-delimited class names, or
    2. An array of class names, or
    3. A map/object of class names to boolean values.

    So, using form 3) we can simply write

    ng-class="{'selected': $index==selectedIndex}"
    

    See also How do I conditionally apply CSS styles in AngularJS? for a broader answer.


    Update: Angular 1.1.5 has added support for a ternary operator, so if that construct is more familiar to you:

    ng-class="($index==selectedIndex) ? 'selected' : ''"
    

提交回复
热议问题