Home >Web Front-end >CSS Tutorial >How Can AngularJS Directives Be Used for Conditional CSS Styling?
Conditional CSS Styling in AngularJS
AngularJS provides various directives to conditionally or dynamically apply CSS styles. These directives include:
To conditionally apply styles, Angular ties a model property to a UI element via ng-model. User input is then used to modify this property, which in turn triggers the relevant directive to update CSS styles.
Example for Q1: Deleting Items
ng-class is suitable for this scenario, where CSS styles are captured in a class. The ng-class expression can be a string, array, or object of class names mapped to boolean values. For checked items, the "pending-delete" class can be applied:
<div ng-repeat="item in items" ng-class="{ 'pending-delete': item.checked }"> ... Item display content ... <input type="checkbox" ng-model="item.checked" /> </div>
Example for Q2: User Personalization
For dynamic CSS styling, ng-style is a better option. It takes an expression that evaluates to an object of CSS style names mapped to values. For example, a user's chosen background color can be set:
<div class="main-body" ng-style="{ color: myColor }"> ... <input type="text" ng-model="myColor" placeholder="Enter a color name" /> </div>
The above is the detailed content of How Can AngularJS Directives Be Used for Conditional CSS Styling?. For more information, please follow other related articles on the PHP Chinese website!