有三種方法:
1、通過$scope綁定(不推薦)
2、通過對象數組綁定
3、通過key/value鍵值對綁定
實現方法:
1、通過$scope綁定(不推薦):
- function ctrl($scope) {
- $scope.className = "selected";
- }
- <div class="{{className}}"></div>
2、通過對象數組綁定:
- function ctrl($scope) {
- $scope.isSelected = true;
- }
- <div ng-class="{true:'selected',false:'unselected'}[isSelected]"></div>
當isSelected爲true時,增加selected樣式;當isSelected爲false時,增加unselected樣式。
3、通過key/value鍵值對綁定:
- function ctrl($scope) {
- $scope.isA = true;
- $scope.isB = false;
- $scope.isC = false;
- }
- <div ng-class="{'A':isA,'B':isB,'C':isC}"></div>
當isA爲true時,增加A樣式;當isB爲true時,增加B樣式;當isC爲true時,增加C樣式。
- <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>
幾點說明:
1、不推薦第一種方法,因爲controller $scope應該只有數據和行爲
2、ng-class是增加相關樣式,可以和class同時使用