如何使用转发器中的复选框AngularJs计算值

时间:2017-01-26 16:46:14

标签: javascript html angularjs

我使用带有复选框的ngRepeat,当我检查每个项目时需要计算所选项目的总值,如下所示:

HTML:

 <tr ng-repeat="ciclo in ciclos">
   <td><input id="idCiclo" type="checkbox" ng-click="computeTotal(ciclo)">
   </td>
   <td>{{ciclo.Quantity}}</td>
   <td>{{ciclo.Value | currency}}</td>
    ...
<tfoot>
 <tr>
  ...
  <td>{{TotalQuantity}}</td>...

控制器:

 $scope.computeTotal = function (ciclo) {
   $scope.TotalQuantity += ciclo.Quantity; //Here I need Add or Subtract a value 
 };

1 个答案:

答案 0 :(得分:2)

您应该有一个属性,指示是否已选中或取消选中复选框,以便您可以决定添加或减去。

您将ngModelngChange一起使用(对于没有内置点击期望/行为的元素,ngClick通常会更好。)

示例:

查看:

<tr ng-repeat="ciclo in ciclos">
   <td>
        <input class="ciclo" type="checkbox" ng-model="ciclo.checked" ng-change="computeTotal(ciclo)">
   <!-- Note that I took out the ID. IDs should never be used in ngRepeat,
        as it heavily risks multiple elements having the same ID,
        which should ALWAYS be unique.
        A class works much better for collections like this. -->
   </td>
   <td>{{ciclo.Quantity}}</td>
   <td>{{ciclo.Value | currency}}</td>
</tr>

控制器:

$scope.computeTotal = function (ciclo) {
    if(ciclo.checked)
        $scope.TotalQuantity += ciclo.Quantity;
    else
        $scope.TotalQuantity -= ciclo.Quantity;
};