Objective
Development often encounter such a requirement, an element needs to appear in different state different appearance, and in this so-called appearance of course is to change its css
attributes, and realize dynamic change attribute value, we need to implement dynamic replacement of its class
property values.
Here to introduce three ways to achieve, we can according to their own needs to choose the way, below to see.
The first: bidirectional binding through data (not recommended)
<div ng-controller= "Firstcontroller" >
<div ng-class= "{{className}}" ></div>
</div >
<script>
var app=angular.module ("MyModule", [])
app.controller (' Firstcontroller ', function ($scope) {
$scope. classname= ' change ';
})
</script>
Online various not recommended, to tell the truth, since angularjs two-way data binding so hanging, why not through this to change it! Check the bottom of the original by: "In the context controller
classname
of what I think is always so weird, I hope is controller
a clean pure JavaScript meaning object
," of course, there is no clear text fixed cannot be so used, and instead I think it is very convenient, Let the elements in HTML change how they want to be! In the img
same element of the src
same can not be changed by other, but in this way is possible! Of course, this kind of way also really gives a person's feeling strange, personally think: can have the last resort
Second: Through an array of objects
<div ng-controller= "Firstcontroller" >
<div ng-class= "{true: ' Change1 ', false: ' Change2 '}[classname]" ></div>
</div>
<script>
var app=angular.module ("MyModule", [])
App.controller (' Firstcontroller ', function ($scope) {
$scope. classname=true;
})
</script>
The implementation is simple, when className
the time is for, the opposite is true true
class
change1
change2
.
But a little bad can only allow an element to have two states, though so to speak! Basic is also satisfied with the need, I usually use this. Simple, Intuitive!
The third type: through Key/value
<div ng-controller= "Firstcontroller" >
<div ng-class= "{' Change1 ': Select, ' change2 ': choice, ' change3 ': Lala} ">
</div>
<script>
var app=angular.module (" MyModule ", [])
App.controller (' Firstcontroller ', function ($scope) {
$scope. select=true;
$scope. lala=true;
})
</script>
When lala
for, true
class
then change3
, personally think this is more recommended, can make up for the second way of the point of regret ~
Summarize
If we can flexibly use these instructions in the project will bring us a lot of convenience, we can solve the problem when there are more ideas, so that we can combine the use of these instructions to quickly solve some of the more distressed problems! The above is the entire content of this article, I hope that you want to learn or work to bring certain help, if there are questions you can message exchange.