Home >Web Front-end >CSS Tutorial >How Can I Conditionally Apply Classes in AngularJS?

How Can I Conditionally Apply Classes in AngularJS?

Susan Sarandon
Susan SarandonOriginal
2024-12-16 07:43:11983browse

How Can I Conditionally Apply Classes in AngularJS?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn