Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 389
Roli Agrawal Avatar asked Apr 21 '15 14:04

Roli Agrawal


1 Answers

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))}}"
like image 109
Satpal Avatar answered Oct 05 '22 23:10

Satpal