Home  >  Article  >  php教程  >  A brief discussion on how to use ng-class in AngularJS

A brief discussion on how to use ng-class in AngularJS

高洛峰
高洛峰Original
2016-12-07 10:33:101314browse

There are three methods:

1. Binding through $scope (not recommended)
2. Binding through object array
3. Binding through key/value pairs

Implementation method:

1. Through $scope Binding (not recommended):

function ctrl($scope) { 
  $scope.className = "selected";
}

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

2. Binding through object array:

function ctrl($scope) { 
  $scope.isSelected = true;
}

<div ng-class="{true:&#39;selected&#39;,false:&#39;unselected&#39;}[isSelected]"></div>

When isSelected is true, increase the selected style; when isS When elected is false , add unselected style.

3. Binding through key/value pairs:

function ctrl($scope) { 
  $scope.isA = true;
  $scope.isB = false;
  $scope.isC = false;
}

<div ng-class="{&#39;A&#39;:isA,&#39;B&#39;:isB,&#39;C&#39;:isC}"></div>

When isA is true, add style A; when isB is true, add style B; when isC is true, Add C style.

<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>

Create ion-item based on the projects loop. When the activeProject is the project currently looped to, add the active style.

Some notes:

1. The first method is not recommended because controller $scope should only have data and behavior

2. ng-class adds related styles and can be used together with class


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn