Table row color according to the result

I am new to AngularJs. I get json data that are in the format:

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

I want to calculate each grade of students and if the grade is less than 40%, then the row of the table should be red and the other should be green. I've 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 get the percentage, but according to the percentage, I don't get the color of the row.

+6
javascript jquery angularjs
source share
3 answers

You need ngClass

The ngClass directive allows you to dynamically set CSS classes in an HTML element by attaching an expression that represents all the classes that you want to add.

the code

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

OR, From a comment by @RevanProdigalKnight

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

when calling a function with ngIf , you do not need string interpolation.

Using

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

instead

 ng-if="{{co(per(x))}}" 
+9
source share

Use ng-class

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

References:

  • How to conditionally apply CSS styles in AngularJS?
  • What is the best way to conditionally apply a class?
+4
source share

ng-if will actually remove the line from the DOM if it is below 40%.

You need

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

As a side note, it is recommended that you do not use functions in ng repeats, as performance can be significantly affected.

+1
source share

All Articles