如何在Angular.js中使用指令基于单元格值更改表格单元格背景色

时间:2019-05-13 14:17:05

标签: angularjs

我有一个表,用于显示将医疗保险分配给受益人的数据。我需要添加一个条件,以检查成员使用量超过初始分配的70%的值,在这种情况下,显示该值背景的单元格将在鼠标悬停时发生变化。

到目前为止,我只能从后端服务中获取所有数据并将其呈现在表上。

我的代码实现如下:

<div class="panel-body">
  <div class="form-group col-sm-12" style="max-height: 400px; overflow-y: auto;">
    <table class="table table-bordered table-striped table-responsive input-sm">
      <thead>
        <tr>
          <th>
            <div class="th"><b>HEALTH BASKET</b></div>
          </th>
          <th >
            <div class="th"><b>ALLOCATION</b></div>
          </th>
          <th >
            <div class="th"><b>USAGE</b></div>
          </th>
          <th >
            <div class="th"><b>BALANCE</b></div>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr data-ng-repeat="voucher in vouchers">
          <td>{{voucher.voucherName}}</td>
          <td>{{voucher.value}}</td>
          <td >{{voucher.used}}</td>
          <td>{{voucher.amountRemaining}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

有什么想法可以使用Angular指令实现吗?

1 个答案:

答案 0 :(得分:0)

您需要使用伪指令ng-mouseoverng-mouseleaveng-class

在您的<tbody>中:

<tbody>
    <tr data-ng-repeat="voucher in vouchers" ng-class="{'usage-exceeded': usageExceeded}" ng-mouseover="checkUsage(voucher)" ng-mouseleave="usageExceeded = false">
        <td>{{voucher.voucherName}}</td>
        <td>{{voucher.value}}</td>
        <td >{{voucher.used}}</td>
        <td>{{voucher.amountRemaining}}</td>
    </tr>
</tbody>

在控制器功能内:

$scope.checkUsage = function (voucher) {
    // add the logic to set the $scope.usageExceeded as true, change this logic as per
    // your condition
    if ((voucher.used / voucher.value) * 100 > 70) {
        $scope.usageExceeded = true;
    }
};

现在,在css中添加css类usage-exceeded,这将更改背景颜色。

.usage-exceeded {
    background-color: red;
}