Angular ng-class explanation and instance code, angularng-class
In the previous experiences of Angularjs development, we mentioned that in angular development, angular controller never contains DOM elements (html/css) and requires a simple POJO (plain object javascript object) in the controller ), fully isolated from view (interacting with angularjs framework responsibilities. However, in some projects, the most common element involved in the controller DOM is to define a variable on the controller scope. Its value is class name, as shown in the following figure:
function ctr($scope){ $scope.test =“classname”;}<div class=”{{test}}”></div>
This method is completely correct. angular provides a way to change the class, but it is always so strange to me that the controller involves classname, what I want is that controller is a clean and pure javascript object.
In angular, we provide three solutions for class processing:
1: bind the scope variable, as shown in the preceding example. (Not recommended)
2: String Array format.
3: Object key/value processing.
We continue with the following two solutions:
1. The String Array form is a simple change to the class, with exclusive changes, true is what class, false is what class, and its shape is like;
function Ctr($scope) { $scope.isActive = true;}<div ng-class="{true: 'active', false: 'inactive'}[isActive]"></div>
The result is a combination in 2. If the isActive expression is true, it is active and inactive.
2. Object key/value processing mainly targets complex class mixing, which is like:
function Ctr($scope) { }<div ng-class {'selected': isSelected, 'car': isCar}"></div>
When isSelected = true, the selected class is added,
When isCar = true, the car class is added,
Therefore, you may have four combinations.
We recommend using two or three methods. We do not recommend that you put the class on the controller scope. The scope must be pure. 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!