在角度方面,我需要根据不同的条件应用不同的样式属性,但它不能以这种方式工作,我只能应用条件表达式的2个条件。
<div ng-style="
(status=="up") ?{'background-color':'green' ,'color':'green'}
(status=="down")?{'background-color':'red' ,'color':'red'}
(status=="idle")?{'background-color':'yellow','color':'yellow'}
(status=="") ?{'background-color':'grey' ,'color':'grey'}
">
如果你知道任何方法将属性传递给一个返回样式obj的函数会更好,对于像nglow这样的ng-style,这很奇怪!
$scope.styleFn(status,attr) {
(status=="up") ?{attr:'green'}
(status=="down")?{attr:'red'}
(status=="idle")?{attr:'yellow'}
(status=="") ?{attr:'grey'}
}
<div ng-style="styleFn('up','background-color')">
答案 0 :(得分:2)
是的,您可以使用函数指定更复杂的条件。
var style = {
'up': {'background-color':'green' ,'color':'green'},
'down': {'background-color':'red' ,'color':'red'},
'idle': {'background-color':'yellow' ,'color':'yellow'},
'default': {'background-color':'grey' ,'color':'grey'}
}
$scope.applyStyle = function(status) {
//the status is the key to get the target style
return status ? style[status] : style['default'];
)};
然后是模板
<div ng-style="applyStyle(status)"></div>
答案 1 :(得分:1)
您也可以使用ng-class。
function DemoCtrl($scope) {
$scope.status = 'up'
}
.green {
color: green;
background-color:green;
}
.red {
color: red;
background-color:red
}
.yellow {
color: yellow;
background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<table ng-controller="DemoCtrl">
<tr ng-class="{'green': status == 'up','red':status== 'down' ,'yellow': status== 'idle' } ">
<td style="color:white;">Your status is {{status}}</td>
</tr>
</table>
</div>