如何在 AngularJS ng-repeat中对 Json 数组值求和

How to Sum a Json Array value in AngularJS ng-repeat

本文关键字:Json 数组 求和 中对 ng-repeat AngularJS      更新时间:2023-09-26

我想对使用 JSON 数组动态添加的产品计数求和。

               <tr ng-repeat="(key,val) in form.products">
                    <td>{{ProductName(key)}}</td>
                    <td >
                        <input type="text" name="products" ng-model="form.products[key]" class="form-control">
                    </td>
                </tr>

如何获取上述示例中的产品总和?

使用 lodash

假设您要求和的值位于名为"price"的属性中:

{{_(form.products).mapValues('price').sum()}}

您可能需要先将 Lodash 纳入您的范围。 在控制器中,如下所示:

scope._ = _;

或者这种方法

您使用的是"具有属性的对象"而不是"对象数组",这就是为什么您不能使用上面的示例,$scope.products.length;...。

您的产品对象及其属性:

$scope.products ={
"1":"20",//property 1 with value 20
"2":"35",//property 2 with value 35
"3":"150"//property 3 with value 150
}

数据对象(具有您拥有的属性的对象):

 $scope.myData = {"1":120,"2":250,"3":500};

迭代对象属性并对价格求和的函数

//read object properties and sum price
    $scope.calculateSum = function(data){
    var sum=0;  
    var counter=0;
     for (var property in data) {
       if (data.hasOwnProperty(property)) {
          sum += data[property];
          counter++;
       }
     }
     return sum;
    };

迭代对象属性并计算乘积的函数

//read object properties and count the products
   $scope.countProducts = function(data){
    var counter=0;
     for (var property in data) {
       if (data.hasOwnProperty(property)) {
          counter++;
       }
     }
     return counter;
    };

进入您的 HTML 模板:

  <table>
  <tr ng-repeat="(key,value) in myData track by $index">
   <td>
        <input type="text" name="id" ng-model="key" class="form-control">
  </td>
   <td>      
      <input type="text" name="price" ng-model="value" class="form-control">            
   </td>
  </tr>
  <tr>
    <td>Products: {{countProducts(myData)}}</td>
    <td>Sum: {{calculateSum(myData)}}</td>
  </tr>
  </table>

我做了一个活生生的例子,计算产品并汇总产品价格:http://plnkr.co/edit/FmJhvV?p=preview

希望有帮助,祝你好运。