【问题标题】:Table row colour according to result根据结果​​的表格行颜色
【发布时间】:2015-06-28 18:37:43
【问题描述】:

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

我得到百分比,但根据百分比我没有得到行颜色。

【问题讨论】:

  • 刚接触 angularjs 时最好不要使用任何 jQuery
  • 我实际上没有看到 jQuery 被用在了哪里。
  • 我认为很多人将 jQuery 与 Javascript 混淆了。
  • Jquery 和 AngularJS 不能共存吗? :) 还没有开始使用 Angular,但我正在使用 Jquery
  • @JaredT,是的,但是,你会遇到很多 Angular 纯粹主义者说你永远不应该同时使用 jQuery 和 Angular。我不同意。从理论上讲,这是一个很棒的概念。实际上,它只是让一些事情变得更容易使用 jQuery。

标签: javascript jquery angularjs


【解决方案1】:

你需要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="co(per(x)) ? 'pass' : 'fail'"
  • @RevanProdigalKnight 我今天学到了一些新东西!我不知道你可以在 ng-class 中使用三元运算符。谢谢!
【解决方案2】:

使用ng-class

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

参考文献:

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

【讨论】:

  • 次要修复...课程应该是通过和失败,而不是绿色和红色。
【解决方案3】:

ng-if 如果该行低于 40%,则实际上会从 DOM 中删除该行。

你会想要的

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

附带说明,建议不要在 ng-repeats 中使用函数,因为性能可能会受到严重影响。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多