问题
In angular, I need to apply different style attributes based on different conditions but its not working this way and I only can apply 2 conditions with conditional expression.
<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'}
">
It would be better if you know any way to pass attribute to a function that returns style obj for ng-style like bellow which is weirdly not working!
$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')">
回答1:
yes you can use a function to specify a more complex condition.
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'];
)};
then the template
<div ng-style="applyStyle(status)"></div>
回答2:
You can use ng-class as well.
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>
来源:https://stackoverflow.com/questions/44210899/how-to-apply-multiple-styles-based-on-multiple-conditions-in-ng-style-directive