In development, we usually encounter a requirement: an element needs to show different appearances in different states.
And in this so-called appearance, of course, is to change its css attributes, and to achieve dynamically changing its attribute value, it must be to replace its class attributes
Here are three methods:
The first type: Bidirectional binding through data (not recommended)
The second type: through an object array
The third type: pass key/value (recommended)
Here are the three types:
The first type: bidirectional binding through data
Implementation method:
function changeClass(){ $ = "change2"; } <div class="{{className}}"></div>
It is not recommended online. To be honest, since angularJS two-way data binding is so arrogant, why can't we change it through this! I checked the reason: "The controller involved classname in my opinion is always so weird. What I hope is that the controller is a clean object with pure JavaScript meaning." Of course, it is not a plain text that cannot be used like this. On the contrary, I think this is very convenient, so that the elements in the html can change whatever they want! Similarly, the src in the img element cannot be changed through other things, but this is possible!
Of course, this method does give people a strange feeling. I personally think: I can do it as a last resort~
The second type: change through the form of a string array
Implementation method:
function changeClass(){ $ = true/false; } <div ng-class="{true:'zhende',false:'jiade'}[className]"></div>
The implementation is very simple, that is, when className is true, class is zhende, and vice versa.
But there is one thing that can only allow one element to have two states, although that's it! It basically meets the needs, and I usually use this. Simple and intuitive!
The third way: through key/value
Implementation method:
function changeClass(){ $ = true; } <div ng-class="{'selectClass':select,'choiceClass':choice,'haha':lala}"></div>
When lala is true, class is haha. I personally think this is more recommended and can make up for the regrets of the second method~
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.