用angularjs计算重复项目的小计

sum sub totals of repeated items with angularjs

本文关键字:项目 angularjs 计算      更新时间:2023-09-26

我试图计算与角表中重复项目的总数。我能算出每个项目的小总额但要算出所有项目的总和才是问题所在

.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>

您可以使用一个函数来计算总金额,

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

你可以像

那样初始化总价值
<td width="16%" ng-init="total=total+item.price"><div align="center">{{item.price}}</div></td>

,然后在你的total中加上

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