There are three ways:
1. Bind with $scope (not recommended)
2. Bind by object array
3. Bind by key/value pair
Implementation method:
$scope binding (not recommended) :
function ctrl($scope) {
$scope.className = "selected";
}
Copy the code
<div class="{{className}}"></div>
Copy the code
2, through object array binding:
function ctrl($scope) {
$scope.isSelected = true;
}
Copy the code
<div ng-class="{true:'selected',false:'unselected'}[isSelected]"></div>
Copy the code
When isSelected is true, add the selected style. Add the unselected style when isSelected is false.
Key /value pair binding:
function ctrl($scope) {
$scope.isA = true;
$scope.isB = false;
$scope.isC = false;
}
Copy the code
<div ng-class="{'A':isA,'B':isB,'C':isC}"></div>
Copy the code
Add A style when isA is true; When isB is true, add B style; When isC is true, the C style is added.
<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>
Copy the code
Ion-item is created from the Projects loop, and the active style is added when activeProject is the project currently looping to.
A few notes:
The first method is not recommended because controller $Scope should only have data and behavior
Ng-class can be used with class