【问题标题】:ng-repeat: Color table background dynamicallyng-repeat:动态地为表格背景着色
【发布时间】:2018-09-15 21:22:31
【问题描述】:

我想根据ng-repeat 产生的值设置表格单元格的背景。到目前为止,我有以下代码:

<table id="myTableDisk" width="100%" border="1">
  <tbody>
    <tr>
      <th scope="col">Mount</th>
      <th scope="col">Size</th>
      <th scope="col">Used</th>
      <th scope="col">Free</th>
      <th scope="col">Use %</th>
    </tr>
    <tr ng-repeat="mount in msg.payload"
        ng-style="{backgroundColor: $scope.getBackgroundColor(mount.usedPercent)}"
        $scope.getBackgroundColor(value) {
            if(value <= 75)
              return 'red';
            if(value > 90)
              return 'blue';
            return 'black'
    }>
      <th align="left" scope="row">{{mount.mount}}</th>
      <td align="right">{{mount.size}}</td>
      <td align="right">{{mount.used}}</td>
      <td align="right">{{mount.available}}</td>
      <td align="right">{{mount.usedPercent}}</td>
    </tr>
  </tbody>
</table>

现在我不得不对这段代码提出问题:

  1. 它不起作用
  2. 如果可行,我认为它会为整个表格着色,但我只需要在 {{mount.usedPercent}} td 上工作

在 Angular 中实现这一点的实用方法是什么?

【问题讨论】:

    标签: html angularjs angularjs-ng-repeat


    【解决方案1】:

    参考 1。您应该在控制器中定义 $scope.getBackgroundColor() 函数,而不是在模板中。

    另请注意$scope 属性和方法可以在模板的表达式中访问,而无需在它们前面加上$scope。如果您在它们前面加上$scope,您实际上是在尝试访问不存在的$scope.$scope.someProperty(除非您定义它们,但是要避免定义$scope$scope 属性,因为它会生成混淆并使您的代码更难理解、调试和维护)。

    参考 2。如果您在特定的&lt;td&gt; 上需要它,只需将其放在您需要的地方即可:

    <tr ng-repeat="mount in msg.payload">
      <th align="left" scope="row">{{mount.mount}}</th>
      <td align="right">{{mount.size}}</td>
      <td align="right">{{mount.used}}</td>
      <td align="right">{{mount.available}}</td>
      <td align="right" 
          ng-style="{backgroundColor: getBackgroundColor(mount.usedPercent)}"
      >{{mount.usedPercent}}</td>
    </tr>
    

    如果你真的想在模板中定义someProperty,你绝对不应该在ng-repeat 中这样做(因为这意味着你在ng-repeat 的每次迭代中都会覆盖它,而且效率很低)。
    但是请记住,如果您的应用程序变得越来越复杂并且您在许多地方都这样做,那么在模板中定义范围属性将使您的代码更难维护;很快您将无法弄清楚定义的内容和位置:

    {{getBackgroundColor = value => value <= 75 ? 'red' : value > 90 ? 'blue' : 'black'}}
    <table>
      <tr ng-repeat="mount in msg.payload">
        ...
        <td ng-style="{backgroundColor: getBackgroundColor(mount.usedPercent)}">
          {{mount.usedPercent}}</td>
      </tr>
    </table>
    

    【讨论】:

    • 非常感谢,它有效。不幸的是,不在 Node-Red 中。阅读此内容,我想这与 NR 仪表板使用某种包装的 Angular 并且无法声明应用程序或控制器这一事实有关。
    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2015-12-14
    • 2015-08-15
    • 2013-01-08
    相关资源
    最近更新 更多