Three ways of using ng class in angularjs


In development, we usually meet a requirement: an element needs to show different appearance in different states.

In this case, the so-called appearance of course is to change the properties of its CSS, and the implementation can dynamically change the value of its attributes, which is bound to be the replacement of its class attribute

There are three ways:

The first one: bidirectional binding through data (not recommended)

The second: through the object array

The third one is through key / value

Here are the three types:

The first one: through the bidirectional binding of data

Implementation mode:

function changeClass(){
  $scope.className = "change2";

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

All kinds of online are not recommended. To be honest, since angularjs bidirectional data binding is so suspended, why can’t we change it through this! I checked the reason: “it seems to me that the controller involves classname. What I hope is that the controller is a clean and pure JavaScript object”. Of course, there is no fixed plaintext that can not be used in this way. On the contrary, I think it is very convenient to let the elements in HTML change as they want! Similarly, the Src in img element can not be changed by other methods, but it can be done in this way!

Of course, this way does give people a strange feeling, I think: can have to do it~

The second way: through the form of string array to change

Implementation mode:

function changeClass(){
  $scope.className = true/false;
<div ng-class="{true:'zhende',false:'jiade'}[className]"></div>

The implementation is very simple, that is, when the classname is true, the class is Zhende and vice versa.

But there’s one thing that’s not good. One element can only have two states, though! Basically, I use this one. Simple and intuitive!

The third way: through key / value

Implementation mode:

function changeClass(){
  $scope.lala = true;
<div ng-class="{'selectClass':select,'choiceClass':choice,'haha':lala}"></div>

When Lala is true, class is haha. I think this is more recommended and can make up for some regrets in the second way~

So basically, there are three ways to implement ng class in angularjs~

Recommended Today

Front end interview day 3 + 1 – 603

Today’s knowledge point (December 09, 2020) – day 603(I’m going to ask questions, too) [html] How to solve the problem of wechat browser video click automatic full screen? [css] What’s the difference between the value preserve-3d of the property transfrom of CSS3 and the value perspective? [js] Tell me about your understanding of built-in objects […]