SoFunction
Updated on 2025-04-04

Angular ng-class detailed explanation and example code

In the previous summary of some experience in Angularjs development, we said that in angular development, the angular controller never contains DOM elements (html/css). The controller needs a simple POJO (plain object javascript object) and is completely isolated from the view (the responsibility of the interactive angularjs framework. However, in some projects, the controller sees that the controller involves the DOM elements is the most defined variable on the controller scope, whose value is class name, and the shape is:

function ctr($scope){
  $ =“classname”;
}

<div class=”{{test}}”></div>

This method is absolutely correct. It is a way to change the class provided by angular, but the controller involves classname in my opinion is always so weird. What I hope is that the controller is a clean pure javascript object.

In angular, we provide 3 solutions to handle class:

1: scope variable binding, as shown in the above example. (Not recommended)
2: String array form.
3: Object key/value processing.

We continue with two other solutions:

1 The string array form is a simple change in class and has repulsive changes. What is true class, what is false class, its shape is like;

function Ctr($scope) { 
  $ = true;
}

<div ng-class="{true: 'active', false: 'inactive'}[isActive]">
</div>

The result is that the combination in 2, and the isActive expression is true, then active is responsible for inactive.

2 object key/value processing is mainly aimed at complex class mixing, which is like:

function Ctr($scope) { 

}

<div ng-class {'selected': isSelected, 'car': isCar}">
</div> 


When isSelected = true, selected class is added.

When isCar=true, add car class.

So you might end up with 4 combinations.

I personally recommend using 2 or 3 methods. It is not recommended to put the class on the controller scope. The scope needs to be kept pure, and the scope can only be data and behavior.

The above is a detailed explanation of Angular ng-class. We will continue to add relevant information in the future. Thank you for your support for this site!