Turn from: 50802136
Other posts Ng-class How to use: 78340922
There are three ways to do this:
1. Binding via $scope (not recommended)
2. Binding by Object array
3. Binding by Key/value key value pair
Implementation method:
1. Binding via $scope (not recommended):
[JavaScript]View PlainCopyPrint?
- function Ctrl ($scope) {
- $scope. ClassName = "selected";
- }
Function Ctrl ($scope) { $scope. ClassName = "Selected";}
[HTML]View PlainCopyPrint?
- < Div class="{{className}}"></div>
<div class= "{{className}}" ></div>
2. Binding by Object array:
[JavaScript]View PlainCopyPrint?
- function Ctrl ($scope) {
- $scope. isSelected = true;
- }
Function Ctrl ($scope) { $scope. isSelected = true;}
[HTML]View PlainCopyPrint?
- < Div ng-class="{true: ' selected ', false: ' unselected '}[isselected]"> </ Div >
<div ng-class= "{true: ' selected ', false: ' unselected '}[isselected]" ></div>
When IsSelected is true, the selected style is added, and when isselected is false, the unselected style is added.
3. Bind by Key/value key value pair:
[JavaScript]View PlainCopyPrint?
- function Ctrl ($scope) {
- $scope. IsA = true;
- $scope. IsB = false;
- $scope. IsC = false;
- }
Function Ctrl ($scope) { $scope. IsA = true; $scope. IsB = false; $scope. IsC = false;}
[HTML]View PlainCopyPrint?
- < Div ng-class="{' A ': IsA, ' B ': IsB, ' C ': IsC}"></Div >
<div ng-class= "{' A ': IsA, ' B ': IsB, ' C ': IsC}" ></div>
When Isa is true, a style is added, and when the ISB is true, the B style is added, and when ISC is true, the C style is added.
[HTML]View PlainCopyPrint?
- < ion-list >
- < Ion-item ng-repeat="project in Projects" ng-click= "Selectproject (Project, $index)" ng-class="{active: ActiveProject = = Project} ">
- {{Project.title}}
- </ Ion-item >
- </ ion-list >
<ion-list><ion-item ng-repeat= "project in Projects" ng-click= "Selectproject (Project, $index)" ng-class= "{ Active:activeproject = = Project} ">{{project.title}}</ion-item></ion-list>
Creates a ion-item based on the projects Loop, adding an active style when ActiveProject is the current loop to project.
A few notes:
1, the first method is not recommended, because the controller $scope should have only data and behavior
2, Ng-class is to add the relevant style, can be used in conjunction with class
How to use Ng-class in Angularjs