2

我有这张表显示软件日志,它由 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”,则其在表中的条目应为红色背景,如果严重性为“MESSAGE”,则应为绿色等。

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

有什么建议么?

4

2 回答 2

3

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;
}
于 2015-05-17T15:50:26.293 回答
2

与上面相同,但带有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>

于 2015-05-17T15:27:41.053 回答