我有1个div,我想有条件地设置这个类的背景颜色属性。我正在使用boostrap progress bar,我只想使用下面的类,因为它包含一些进度条的自定义设置。
以下是我的div:
.statistics .progress-bar {
background-color: black;
border-radius: 10px;
line-height: 20px;
text-align: center;
transition: width 0.6s ease 0s;
width: 0;
}
<div class="statistics" ng-repeat="item in data">
<div class="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" ng-style="{'width' : ( item.statistics + '%' )}">
</div>
</div>
条件如下:
If statistics > 100
backgroundcolor=red;
else
backgroundcolor=black;
答案 0 :(得分:3)
您可以使用简单表达式
来完成ng-style="<condition> ? { <true-value> } : { <false-value> }"
<强>输出强>
<强>代码:强>
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<div ng-style="item.statistics > 100 ? { 'background-color':'red', 'width': item.statistics + '%' }: { 'background-color':'yellow', 'width': item.statistics + '%'}">
<h2>$scope.statistics = {{statistics}}</h2>
</div>
<div ng-style="item.statistics2 > 100 ? { 'background-color':'red', 'width': item.statistics2 + '%' } : { 'background-color':'yellow', 'width': item.statistics2 + '%'}">
<h2>$scope.statistics2 = {{statistics2}}</h2>
</div>
<script>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", ['$scope', function($scope) {
$scope.item = {};
$scope.item.statistics = 30;
$scope.item.statistics2 = 101;
}]);
</script>
</body>
</html>
答案 1 :(得分:1)
您可以使用ng-class动态设置css类
.statistics .progress-bar {
background-color: black;
border-radius: 10px;
line-height: 20px;
text-align: center;
transition: width 0.6s ease 0s;
width: 0;
color: black
}
.red {
color: red
}
<div class="progress-bar" role="progressbar"
aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100"
ng-style="{'width' : ( item.statistics + '%' )}"
ng-class="{ red: item.statistics > 100 }"
>
如果您不想创建额外的课程,可以使用ng style:
<div class="progress-bar" role="progressbar"
aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100"
ng-style="getItemStyle(item)">
然后在你的控制器中,你必须创建getItemStyle函数:
$scope.getItemStyle = function(item) {
// determine the color
var itemColor = item.statistics > 100 ? 'red' : 'black';
// return object containing the css props
return {
'width': item.statistics + '%',
'color': itemColor
};
};
答案 2 :(得分:0)