how to combine conditional class and data bound class in angularjs

社会主义新天地 提交于 2019-12-22 06:40:09

问题


To apply different classes when different expressions evaluate to true:

<div ng-class="{'class1' : expression1, 'class2' : expression2}">
    Hello World!
</div>

To apply different classes a data-bound class using []

 <div ng-class="[class3, class4]">
        Hello World!
    </div>

I want to know if it is possible to combine the two types of template, i.e; have a conditional class using {} and a data-bound class using []?

Any help would be greatly appreciated.

Thanks in advance.


回答1:


You can use following syntax

<div ng-class="[condition1 && 'class1', condition2 && 'class2', className]">
    Hello World!
</div>

className is a variable in scope. It's value gets applied to div.

Here is a example fiddle Conditionally apply class in angularjs




回答2:


Please see demo below

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {


  $scope.redClass = 'red';
  $scope.boldClass = 'bold';

});
.border {
  border: 1px solid red
}
.red {
  color: red
}
.bold {
  font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="homeCtrl">

    <p ng-class="[boldClass ,redClass,  1==1 ? 'border':'' ]">Hello Word</p>

  </div>
</div>


来源:https://stackoverflow.com/questions/29230732/how-to-combine-conditional-class-and-data-bound-class-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!