簡體   English   中英

根據結果​​表行顏色

[英]Table row colour according to result

我是AngularJs的新手我正在獲取格式的json數據:

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

我想計算每個學生的分數,如果分數小於40%,那么表格行應該是紅色,否則應該是綠色。 我努力了。 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>

腳本

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;} 

我得到百分比,但根據百分比,我沒有得到行顏色。

你需要ngClass

ngClass指令允許您通過數據綁定表示要添加的所有類的表達式來動態設置HTML元素上的CSS類。

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

或者 ,來自@RevanProdigalKnight評論

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

當用ngIf調用函數時,你不需要字符串插值。

采用

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

代替

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

使用ng-class

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

參考文獻:

  1. 如何在AngularJS中有條件地應用CSS樣式?
  2. 有條件地申請課程的最佳方式是什么?

ng-if實際上會從DOM中刪除該行,如果它低於40%。

你想要的

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

作為旁注,建議不要在ng-repeats中使用函數,因為性能會受到很大影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM