2

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?

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

To make it cleaner, a directive which accepts the log severity and switches the class would be a good design decision.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.