Elegant Solutions for Conditionally Applying Classes in AngularJS
When displaying an array of elements, you may encounter the need to highlight a specific element based on a property. In AngularJS, this conditional application of classes can be achieved in several ways.
One simple solution, although not ideal, is to manually duplicate the list element (li) and add a class to the one corresponding to the selected index. However, AngularJS provides more sophisticated methods to achieve this task.
Expression-Based Class Assignment
To directly add a class to the li with the selectedIndex index, you can use a conditional expression within the ng-class directive:
ng:class="{true:'selected', false:''}[$index==selectedIndex]"
This expression evaluates to either 'selected' if the current index matches the selectedIndex, or an empty string otherwise.
Object-Based Class Mapping
A newer syntax allows you to assign classes based on an expression that returns an object:
ng-class="{selected: $index==selectedIndex}"
In this case, the 'selected' property will be applied as a class if the current index matches the selectedIndex.
Property-to-Class Name Mapping
For a more flexible approach, you can map a model property directly to a class name:
ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"
This expression uses the user.role property to determine which class to apply. For instance, if the user's role is 'admin', the 'enabled' class will be added to the element.
The above is the detailed content of How Can I Conditionally Apply Classes in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!