AngularJS: 动态设置背景色

AngularJS: setting background color dynamically

我有这个 table 显示软件日志,其中填充了 JSON 数据:

<div ng-controller="LogCtrl">
  <table id="logtable" style="width:100%">
    <tr>    
        <th>Timestamp</th>
        <th>Severity</th>
        <th>Message</th>
    </tr>
    <tr ng-repeat="log in logs" class="logentry">
        <td>{{log.timestamp}}</td>
        <td>{{log.severity}}</td>
        <td>{{log.message}}</td>
    </tr>
</table>

它工作正常,但我希望能够根据其严重程度更改每个 tr 元素背景。例如,如果该日志的严重性是 "ERROR",它在 table 中的条目应该有红色背景,如果严重性是 "MESSAGE",它应该是绿色,等等 [=14] =]

我已经看过 ng-style,但我没有找到如何将其用于此目的。

有什么建议吗?

同上,但有 ng-style.

<tr ng-repeat="log in logs"
    ng-style="{'ERROR':{background:'red'}, 'INFO':{background: 'green'}}[log.severity]">
    <td>{{log.timestamp}}</td>
    <td>{{log.severity}}</td>
    <td>{{log.message}}</td>
</tr>

var app = angular.module('app', []);

app.controller('tableController', function($scope) {
  $scope.logs = [
    {
               timestamp: 'foo',
               severity: 'ERROR',
               message: 'Something bad happened'
    },
    {
               timestamp: 'bar',
               severity: 'INFO',
               message: 'This is ok'
    },
  ];
});
<script src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>

<table ng-controller="tableController" ng-app="app">
 <tr ng-repeat="log in logs"
     ng-style="{'ERROR':{background:'red'}, 'INFO':{background: 'green'}}[log.severity]">
   <td>{{log.timestamp}}</td>
   <td>{{log.severity}}</td>
   <td>{{log.message}}</td>
 </tr>
</table>

您可以通过 ng-class 条件运算符

来实现
<tr ng-repeat="log in logs" class="logentry" 
    ng-class="{ 'ERROR': 'severity-error', 'MESSAGE': 'severity-message'}[log.severity]">
    <td>{{log.timestamp}}</td>
    <td>{{log.severity}}</td>
    <td>{{log.message}}</td>
</tr>

CSS

.severity-error {
    background-color: red;
}

.severity-message {
    backgroud-color: green;
}