Roli Agrawal
Roli Agrawal

Reputation: 2466

Table row colour according to result

I am new to AngularJs I am getting json data which is in format:

[
  {
    'StudentName':'abc',
    'maths':'0',
    'english':'0',
    'economics':'0',
  }
] 

I want to calculate each students marks and if marks is less than 40% then table row should be red else else should be green. I have tried. HTML

<div ng-app="MyApp" ng-controller="con1"> 
  <table id="table1">
    <tr>
      <th>student Name</th>
      <th>History Marks</th>
      <th>Maths Marks</th>
      <th>Economics Marks</th>
      <th>Percentage</th>
    </tr>
    <tr ng-repeat="x in data" ng-if="{{co(per(x))}}" ng-class="pass">
      <td>{{x.StudentName}}</td>
      <td>{{x.maths}}</td>
      <td>{{x.economics}}</td>
      <td>{{x.english}}</td>
      <td>{{per(x)}}%</td>
    </tr>
  </table>

Script

var app = angular.module('MyApp', []);
app.controller('con1', function ($scope, $http) {
    $http.get('/ajax/data').success(function (res) { $scope.data = res; });
    $scope.per = function (x) {
        avg = ((parseInt(x.maths) + parseInt(x.economics) + parseInt(x.english)) * 100) / 300;
        return avg;
    };
    $scope.co = function (x) { (x > 40) ? k = 1 : k = 0; return (k); }
});

css

.pass{background:green;}
.fail{background:red;} 

I am getting percentage but according to percentage I am not getting the row colour.

Upvotes: 6

Views: 547

Answers (3)

Satpal
Satpal

Reputation: 133453

You need ngClass

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

Code

ng-class='{ "pass" : co(per(x)) == 1, "fail" : co(per(x)) == 0 }'

OR, From @RevanProdigalKnight comment

ng-class="co(per(x)) ? 'pass' : 'fail'"

when calling function with ngIf, You don;t need string interpolation.

Use

ng-if="co(per(x))"

instead of

ng-if="{{co(per(x))}}"

Upvotes: 9

Tushar
Tushar

Reputation: 87233

Use ng-class

ng-class="{pass: per(x) >= 40, fail: per(x) < 40}"

References:

  1. How do I conditionally apply CSS styles in AngularJS?
  2. What is the best way to conditionally apply a class?

Upvotes: 4

Scottie
Scottie

Reputation: 11308

ng-if will actually remove the row from the DOM if it's below 40%.

You'll want

<tr ng-repeat="x in data" ng-class="{ 'pass' : per(x) > 40 }">

As a side note, it's recommended not to use functions in ng-repeats because performance can suffer significantly.

Upvotes: 1

Related Questions