在AngularJS中,我使用ng-class的方式如下:
<div class="bigIcon" data-ng-click="PickUp()"
ng-class="{first:'classA', second:'classB', third:'classC', fourth:'classC'}[call.State]"/>
我想知道我是否可以使用if-else表达式来做类似的事情:
<div class="bigIcon" data-ng-click="PickUp()"
ng-class="{first:'classA', second:'classB', else:'classC'}[call.State]"/>
所以无论何时调用。状态不同于第一次或第二次使用classC和避免指定每个值?
上面的解决方案对我来说并不适用于有背景图像的类。我所做的是我创建了一个默认类(你需要在else中),并设置class='defaultClass',然后ng-class="{class1:abc,class2:xyz}"
<span class="booking_warning" ng-class="{ process_success: booking.bookingStatus == 'BOOKING_COMPLETED' || booking.bookingStatus == 'BOOKING_PROCESSED', booking_info: booking.bookingStatus == 'INSTANT_BOOKING_REQUEST_RECEIVED' || booking.bookingStatus == 'BOOKING_PENDING'}"> <strong>{{booking.bookingStatus}}</strong> </span>
注:处于condition状态的类应该覆盖默认类,即标记为!important的类
很明显!我们可以用下面的例子创建一个函数来返回一个CSS类名。
CSS
<style>
.Red {
color: Red;
}
.Yellow {
color: Yellow;
}
.Blue {
color: Blue;
}
.Green {
color: Green;
}
.Gray {
color: Gray;
}
.b{
font-weight: bold;
}
</style>
JS
<script>
angular.module('myapp', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
$scope.getClass = function (strValue) {
if (strValue == ("It is Red"))
return "Red";
else if (strValue == ("It is Yellow"))
return "Yellow";
else if (strValue == ("It is Blue"))
return "Blue";
else if (strValue == ("It is Green"))
return "Green";
else if (strValue == ("It is Gray"))
return "Gray";
}
}]);
</script>
然后
<body ng-app="myapp" ng-controller="ExampleController">
<h2>AngularJS ng-class if example</h2>
<ul >
<li ng-repeat="icolor in MyColors" >
<p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
</li>
</ul>
<hr/>
<p>Other way using : ng-class="{'class1' : expression1, 'class2' : expression2,'class3':expression2,...}"</p>
<ul>
<li ng-repeat="icolor in MyColors">
<p ng-class="{'Red':icolor=='It is Red','Yellow':icolor=='It is Yellow','Blue':icolor=='It is Blue','Green':icolor=='It is Green','Gray':icolor=='It is Gray'}" class="b">{{icolor}}</p>
</li>
</ul>
你可以参考ng-class的完整代码页if example
我的一个变通方法是操纵一个模型变量,只是为了ng类切换:
例如,我想根据列表的状态切换类:
1)每当我的列表为空时,我更新我的模型:
$scope.extract = function(removeItemId) {
$scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
if (!$scope.list.length) {
$scope.liststate = "empty";
}
}
2)当我的列表不空时,我设置另一个状态
$scope.extract = function(item) {
$scope.list.push(item);
$scope.liststate = "notempty";
}
3)当我的列表从未被触及时,我想给另一个类(这是页面初始化的地方):
$scope.liststate = "init";
3)我在ng课上使用了这个额外的模型:
ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"