Search code examples
cssangularjsjsonangularjs-ng-repeatng-bind

highlight table data based on winner values obtained from JSON


I am parsing JSON data and displaying the data to a table using angular JS.

There are many table rows that I populated from JSON file using ng-repeat.

Status.winner could be of values 0 or 1.

If the value for the winner for the table row is 0, I would like to highlight Playerdata[0].playername for that table row to yellow color.

Else If the winner for the table row is 1, then I would like to highlight Playerdata[1].playername for that table row to yellow color.

How do I do that for each row with different values of winner, which can be 0 or 1?

<body ng-app="form-input" ng-controller="ctrl">
<table class="table table-bordered table-condensed ">
  <caption>Recent Game Statistic</caption>
  <tbody> 
  <tr class="success"  ng-repeat="status in recentGame">      
    <td ng-bind="status.Winner"> </td> 
    <td ng-bind="status.Playerdata[0].Playername"> </td> 
    <td ng-bind="status.Playerdata[1].Playername"> </td> 
  </tr>  

var app2 = angular.module('form-input', []);

app2.controller('ctrl', function($scope,$http) { 

var url = "http://...JSON";

$http.get(url).success( function(data) { 
  $scope.recentGame = data.RecentGames; 
  });   
})

Solution

  • Use ngClass:

    <tr class="success" ng-repeat="status in recentGame">      
        <td ng-bind="status.Winner"></td> 
        <td ng-bind="status.Playerdata[0].Playername" ng-class="{winner: status.Winner == 0}"></td> 
        <td ng-bind="status.Playerdata[1].Playername" ng-class="{winner: status.Winner == 1}"></td> 
    </tr>
    

    Then in CSS define .winner class styles the way you need. For example:

    .winner {
        background-color: yellow;
    }