Search code examples
javascripthtmlcssangularjsng-style

AngularJS: setting background color dynamically


I have this table showing software logs, which gets populated by JSON data:

<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. 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.

I already took a look at ng-style, but I didn't find out how to use it for this purpose.

Any suggestions?


Solution

  • You can achieve this by ng-class conditional operator

    <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;
    }