In AngularJS, you may encounter scenarios where you need to conditionally apply a class to an element based on certain conditions. Here's how you can achieve this efficiently.
Consider an array of elements rendered as a ul with li tags for each element. You have a selectedIndex property on the controller and want to add a class to the li with the corresponding index.
1. Using ng-class:
AngularJS provides the ng-class directive, which allows you to dynamically apply classes based on expressions. To conditionally apply the class "selected" to the li with the selectedIndex, you can use:
<li ng-class="{selected: $index == selectedIndex}">...</li>
2. Using ng:class:
(Pre-v1 Syntax)
For AngularJS versions prior to v1, you can use ng:class with an expression that evaluates directly to a class name. For instance:
<li ng:class="{true:'selected', false:''}[$index == selectedIndex]">...</li>
While both solutions achieve the same result, they differ in functionality:
You can also use this technique to map model properties to class names, keeping CSS classes out of controller code. For example:
<li ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]">...</li>
The above is the detailed content of How Can I Conditionally Apply CSS Classes to Elements in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!