使用angularjs对重复项目的总计进行求和

时间:2016-10-08 15:57:06

标签: javascript angularjs

我试图用角度来计算表格中重复项目的总数。我总结得到每个项目的子总数,但获得所有项目的总和是问题

.controller('reciept_ctrl',['$scope','$http','$state','$stateParams','$window',function($scope,$http,$state,$stateParams,$window){
    $scope.shop_id=localStorage.getItem("shop_id");
    $scope.payment_id=localStorage.getItem("payment_id");
    $http.get('http://localhost/sales/reciept.php?payment_id='+$stateParams.payment_id + "&shop_id="+$scope.shop_id).success(function(data){
        console.log(JSON.stringify(data));
        $scope.reciept=data;

       });

HTML

    <div ng-repeat="item in reciept">
        <table width="100%" border="0" cellspacing="4" cellpadding="4">
          <tr>
            <td width="50%"><div align="left">{{item.item}}</div></td>
            <td width="16%"><div align="center">{{item.price}}</div></td>
            <td width="12%"><div align="center">{{item.quantity}}</div></td>
            <td width="20%"><div align="center">GH¢ {{item.quantity*item.price}}</div></td>
            </tr>
          <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td colspan="2">&nbsp;</td>
            </tr>
        </table>
        <p>

       </div>

<table width="100%" border="0" cellspacing="1" cellpadding="1">
  <tr>
    <td>Grand Total:</td>
  </tr>
</table>

2 个答案:

答案 0 :(得分:0)

你可以有一个计算总计的函数,

 $scope.getTotal = function(type) {
        var total = 0;
        angular.forEach($scope.items, function(el) {
            total += el[type];
        });
        return total;
    };

DEMO

答案 1 :(得分:0)

您可以初始化总值,如

<td width="16%" ng-init="total=total+item.price"><div align="center">{{item.price}}</div></td>

并且在您的总计中刚刚提出

<td>Grand Total:{{total}}</td>