In AngularJS, applying classes conditionally to elements can be achieved in multiple ways. Let's explore the most optimal solutions based on your specific scenario.
Scenario: An array is rendered as an unordered list, and you wish to add a class to the list item with index selectedIndex controlled by the selectedIndex property on the controller.
Initial Approach:
You are currently manually replicating the list item code and adding the class to one of the list item tags. While this method works, it introduces unnecessary duplication.
Solution 1: ng-class Directive with Evaluated Expressions
Instead of using CSS class names in the controller, you can use an expression to dynamically set the class name. Here's how:
<li ng:class="{true:'selected', false:''}[$index==selectedIndex]"></li>
Note: Use the old syntax with the colon due to the evaluation mechanism required for this approach.
Solution 2: ng-class Directive with Conditional Objects
AngularJS also supports assigning objects to the ng-class directive. Each property name represents a class name, and its value determines if the class is applied.
<li ng-class="{selected: $index==selectedIndex}"></li>
Additional Note:
While both solutions achieve the same result, they are not functionally equivalent. Solution 2 allows you to map model properties to class names and keep them out of the controller code. This provides greater flexibility and improves code readability.
The above is the detailed content of How Can I Efficiently Apply Conditional Classes to List Items in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!