获取Angular中列的总和

时间:2019-07-18 21:06:16

标签: javascript angularjs calculator totals

我无法获得计算出的总额。我该怎么做才能获得第三列的总数?

<body ng-app="Test">
  <section style="margin-top:80px">
    <div ng-controller="TestController as test" >
      <table class="table">
        <tr>
          <th>Name</th>
          <th>Number</th>
          <th>Amount</th>
          <th>Reduced Amount</th>
        </tr>

        <tr ng-repeat="x in test.approve">
          <td> {{ x.name }} </td>
          <td> <input class="qty form-control" type="number" ng-model="x.number" ng-change="sumByColumn3()" min="0" restrict-to="[0-9]"/> </td>
          <td> <span ng-model="x.amount" ng-change="sumByColumn()">{{ x.number*x.amount }}</span> </td>
          <td> <input class="qty form-control" type="number" ng-model="x.reducedAmount" ng-change="sumByColumn2()" min="0" restrict-to="[0-9]"/> </td>
        </tr>
        <tr>
          <td style="color:red;">Totals go here</td>
          <td>{{ test.approve | sumByColumn3: 'number' }}</td>
          <td>{{ test.approve | sumByColumn: 'amount' }}</td>
          <td>{{ test.approve | sumByColumn2: 'reducedAmount' }}</td>
        </tr>
      </table>

    </div>
  </section>


</body>

这是完整的代码。https://codepen.io/tampham/pen/RzqLQV

1 个答案:

答案 0 :(得分:3)

在html的第3列中,您有:

<td> <span ng-model="x.amount" ng-change="sumByColumn()">{{ x.number*x.amount }}</span> </td>

乘法:

x.number * x.amount

但是在这里你想念这个:

.filter('sumByColumn', function () {
      return function (collection, column) {
        var total = 0;

        collection.forEach(function (item) {
          total += parseInt(item[column]);
        });

        return total;
      };
    })

我想如果您加上该乘法,您将得到正确的总数:

parseInt(item[column]*item.number);