Angular Ng-class Detailed and instance code _ANGULARJS

Source: Internet
Author: User

In the previous ANGULARJS development, we said that in angular development angular controller never contains DOM elements (HTML/CSS), and a simple controller is needed in Pojo (plain object JavaScript object), completely isolated from view (the responsibility of interacting angularjs frameworks.) But the most common element in some projects that controller involves DOM is defining a variable on the controller scope with the value class name, like:

Function Ctr ($scope) {
  $scope. Test = "classname";
}

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

This is totally true, angular provides a way to change class, but in controller it's always weird to be involved in classname. What I want is that controller is a clean, pure JavaScript-meaning object.

The angular provides us with 3 solutions for class:

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

We continue with the other two solutions:

The 1 string array form is a simple change to class, with a repulsive change, true what Class,false is and what class it is;

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

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

The result is a combination of 2 and the isactive expression is true, active, and responsible for inactive.

2 Object Key/value processing is mainly for complex class mixing, its shape is as follows:

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,

So you might end up with 4 different combinations.

Personal recommendation in 2, 32 ways, do not recommend class into controller scope, scope needs to remain pure line, scope can only be data and behavior.

The above is the angular ng-class detailed, follow-up to continue to supplement the relevant information, thank you for your support of this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.