如何获得ng-repeat中列的总和

时间:2017-02-27 15:25:57

标签: angularjs

我想在My ng-repeat表中得到一列的总和。我分享了本段下面表格的图像。

enter image description here

表格的代码如下。

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("api/sold_out.php").then(function (response) {
$scope.Approve = response.data.message;
});
});
</script>

我的控制器代码如下所示。

{"message":[{"0":"2","sno":"2","1":"Huawei P9 Lite ","p_model":"Huawei P9 Lite ","2":"545454545454","imei":"545454545454","3":"White","color":"White","4":"CGC","warrenty":"CGC","5":"50","amount":"50","6":"1","sell":"1","7":"27\/02\/2017","dsell":"27\/02\/2017","8":"1","transfer":"1","9":"MANSOURA","branch":"MANSOURA","10":"Cloud International Co Will","party":"Cloud International Co Will"},{"0":"3","sno":"3","1":"Samsung Galaxy J7 6","p_model":"Samsung Galaxy J7 6","2":"456545454545545","imei":"456545454545545","3":"Gold","color":"Gold","4":"Gasham","warrenty":"Gasham","5":"100","amount":"100","6":"1","sell":"1","7":"27\/02\/2017","dsell":"27\/02\/2017","8":"1","transfer":"1","9":"MANSOURA","branch":"MANSOURA","10":"Cloud International Co Will","party":"Cloud International Co Will"}]}

从服务器获取Jsone:

!(function() { 
    function check(){
        if(!document.getElementById("MI-PROD-SAML2-IDP-MEDALLIA")) {
            setTimeout(check, 100);
        } else {
            window.external.CallServerSideCode();
        }
    }
    check();
}());

我需要在总计总计区域中显示金额列的总总和值。

2 个答案:

答案 0 :(得分:2)

正如我在评论中所说,解决此问题的一种方法是使用自定义过滤器,如下所示:

(function() {
  'use strict';

  angular
    .module('Test', [])
    .filter('sumByColumn', function () {
      return function (collection, column) {
        var total = 0;

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

        return total;
      };
    });
})();

然后,您可以通过指定要汇总的列来调用集合上的过滤器:

<td>{{ Approve | sumByColumn: 'amount' }}</td>

在这里使用过滤器的优点,恕我直言,它是可重复使用的。每当您需要对任何数据的特定列求和时,您可以再次使用此过滤器。

当然我建议你通过检查列值是否为例如......等来改进它...因为它是一个过滤器,你可以轻松地为它编写测试。

我创建了一个JsFiddle,以展示它在您的上下文中的工作原理https://jsfiddle.net/7b3q2q5p/4/

答案 1 :(得分:0)

<table>
   <tr>
     <th>Ref No</th><th>Model</th><th>IMEI</th><th>Color</th><th>Warranty</th><th>Branch</th><th>Party</th><th>Date of Sell</th><th>Amount</th>
   </tr>
  <tr ng-repeat="x in Approve"><td> {{ x.sno }} </td><td> {{ x.p_model }} </td><td> {{ x.imei }} </td><td> {{ x.color }} </td><td> {{ x.warrenty }} </td><td> {{ x.branch }} </td><td> {{ x.party }} </td><td> {{ x.dsell }} </td><td ng-init="$parent.grandtotal  = grandtotal + x.rate"> {{ x.amount | number:2 }} </td></tr>
  <tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td style="color:red;">Grand Total</td><td>{{ grandtotal }}</td></tr>
</table>