javascript - 根据结果​​的表行颜色

标签 javascript jquery angularjs

我是 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

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.

代码

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))}}"

关于javascript - 根据结果​​的表行颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29774952/

相关文章:

javascript - 无法摆脱对禁用按钮的悬停效果

javascript - 1000hz 验证器检查最小值、最大值和特定值

jquery - 我可以从 jquery 函数创建 ember 计算属性吗?

javascript - Kendo Grid 自定义弹出编辑器模板中的 jQuery Accordion 向导

javascript - 如何更新 Controller angularjs中的.value?

javascript - 具有多个控件的数据 View

javascript - 带暂停和恢复轮询的 Rxjs 计时器

javascript - $ (".class").width($(this)...) 不起作用

javascript - nw-fileDialog 未捕获错误 : [$injector:modulerr]

javascript - $resource.get 给出 "TypeError: undefined is not a function"