Javascript 如何使用angular js有条件地设置特定的类属性?
我有一个div,我想在其中有条件地设置这个类的背景色属性。我正在使用并且只想在类下使用,因为它包含一些进度条的自定义设置 以下是我的部门:Javascript 如何使用angular js有条件地设置特定的类属性?,javascript,angularjs,ng-class,ng-style,Javascript,Angularjs,Ng Class,Ng Style,我有一个div,我想在其中有条件地设置这个类的背景色属性。我正在使用并且只想在类下使用,因为它包含一些进度条的自定义设置 以下是我的部门: .statistics .progress-bar { background-color: black; border-radius: 10px; line-height: 20px; text-align: center; transition: width 0.6s ease 0s; width: 0; }
.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>
您可以为changin背景属性使用
或者用于类操纵
不要忘记像这样使用对象表示法
data-ng-class = {'test-class': condition}
可以使用ng类动态设置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="<condition> ? { <true-value> } : { <false-value> }"
输出
代码:
$scope.statistics={{statistics}
$scope.statistics2={{{statistics2}
var myApp=angular.modulemyyapp,[];
myApp.controllermyCtrl,['$scope',函数$scope{
$scope.item={};
$scope.item.statistics=30;
$scope.item.statistics2=101;
}];
如果我想设置2种或更多颜色,那么我必须为此创建这么多的类。是的,您可以向ng类添加条件,即ng类={green:item.statistics<50,red:item.statistics>100}例如,抱歉,但我不想创建一个仅用于设置颜色属性的额外类。相反,我只想更新现有类的背景颜色属性。我尝试这样做,但出现错误:ng style={'width':item.statistics+'%,item.statistics>100?{'background color':'a08bcd'}:{'background color':'c1f3ca'}.Syntax错误:令牌“.”意外,应为[}]@Learning。请根据您的最新要求查看我的更新代码。如您所见,背景颜色和宽度也是动态的。我相信它现在会对你有用的。
<div class="progress-bar" role="progressbar"
aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100"
ng-style="getItemStyle(item)">
$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
};
};
ng-style="<condition> ? { <true-value> } : { <false-value> }"