Conditionally Applying Classes in AngularJS with `ng-class`

Introduction

AngularJS, a structural framework for dynamic web apps, provides powerful directives to control DOM elements’ classes dynamically. One such directive is ng-class, which allows you to add or remove CSS classes based on the state of your application’s data model. This tutorial will guide you through using ng-class in various ways to conditionally apply classes in AngularJS.

Understanding ng-class

The ng-class directive can evaluate an expression and apply corresponding CSS classes to an element. It supports several types of expressions:

  1. String: A space-delimited list of class names.
  2. Array: An array of class names.
  3. Object: A map where keys are class names, and values are boolean expressions.

Basic Usage

String or Array Example

<div ng-class="['class1', 'class2']">Content</div>

This will apply both class1 and class2 to the <div> element.

Object Mapping Example

<div ng-class="{active: isActive, disabled: !isEnabled}">Content</div>

Here, if isActive is true, the class active is applied; if !isEnabled evaluates to true (i.e., isEnabled is false), then the class disabled is added.

Conditional Class Application

Using Boolean Expressions

Consider a scenario where you have a list of items and want to highlight an item based on whether it matches the selected index:

<ul>
  <li ng-repeat="item in items" 
      ng-class="{selected: $index == selectedIndex}">
    {{item}}
  </li>
</ul>

In this example, the ng-class directive checks if the current item’s index ($index) matches selectedIndex. If true, it applies the class selected.

Ternary Operator (AngularJS 1.2+)

For AngularJS versions 1.2 and above, a more concise way using the ternary operator is available:

<li ng-repeat="item in items" 
    ng-class="($index == selectedIndex) ? 'selected' : ''">
    {{item}}
</li>

This approach offers cleaner syntax for simple conditions.

Advanced Techniques

Using Controller Functions

For more complex logic, you can define a function within your controller to determine the class:

<ul>
  <li ng-repeat="item in items" 
      ng-class="getClass($index)">
    {{item}}
  </li>
</ul>

In your controller:

function ListCtrl($scope) {
  $scope.items = ['Item 1', 'Item 2', 'Item 3'];
  $scope.selectedIndex = -1;

  $scope.getClass = function(index) {
    return index === $scope.selectedIndex ? 'selected' : '';
  };
}

Leveraging JavaScript Variables

You can also directly bind a JavaScript variable to determine the class:

<li ng-repeat="item in items" 
    class="ng-class:isSelected">
  {{item}}
</li>

In your controller, define isSelected as part of each item object or separately:

function ListCtrl($scope) {
  $scope.items = [
    { name: 'Item 1', isSelected: true },
    { name: 'Item 2', isSelected: false }
  ];
}

Conclusion

The ng-class directive in AngularJS offers a flexible way to conditionally apply CSS classes based on your application’s state. By understanding and using the various supported expressions, including object mapping, ternary operators, and controller functions, you can efficiently manage element styling dynamically. This capability enhances both the functionality and user experience of your web applications.

Leave a Reply

Your email address will not be published. Required fields are marked *