简体   繁体   English

AngularJS:动态设置背景颜色

[英]AngularJS: setting background color dynamically

I have this table showing software logs, which gets populated by JSON data: 我有这张表显示软件日志,该日志由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>

It works fine, but I would like to be able to change each tr element background following its severity. 它工作正常,但是我希望能够根据其严重性来更改每个tr元素的背景。 For example, if the severity of that log is "ERROR", its entry in the table should have red background, if the severity is "MESSAGE", it should be green, etc. 例如,如果该日志的严重性为“ ERROR”,则其在表中的条目应具有红色背景,如果严重性为“ MESSAGE”,则应为绿色,等等。

I already took a look at ng-style , but I didn't find out how to use it for this purpose. 我已经看过ng-style ,但是我没有找到如何将其用于此目的。

Any suggestions? 有什么建议么?

You can achieve this by ng-class conditional operator 您可以通过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 CSS

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

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

Same as above, but with 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM