2016-11-11 87 views
0

我有阵列$scope.otherDetailsData如何总结值迭代

[0] object 
amount: 29.9 
code: "012" 
currency: "BRL" 
payedDate: "2016-11-10" 
roDate: "2016-08-01" 
type:"OTHER" 

[1] object 
amount: 39.9 
code: "013" 
currency: "BRL" 
payedDate: "2016-11-11" 
roDate: "2016-08-01" 
type:"OTHER" 

我的问题是,我怎么能求和数额与总变量? 如:69.8

<span> {{ totalOfSumAmount }} </span> 

回答

0

最简单的(也是最有效)的方法是只写为您完成此功能。

<span> {{ getTotalOfSumAmount() }} </span> 

添加的功能,以您的控制器:

$scope.getTotalOfSumAmount = function() { 
    var runningTotal = 0; 
    for (var i = 0; i < $scope.otherDetailsData.length; i++) { 
     runningTotal += $scope.otherDetailsData[i].amount; 
    } 
    return runningTotal; 
} 
+0

错误:[$插值:INTERR]不能插: \t {{getTotalOfSumAmount()}} – vbotio

0

您可以使用Array.prototype.reduce

$scope.totalOfSumAmount = $scope.otherDetailsData.reduce(function(prev, curr) { 
    return prev + curr.amount; 
}, 0); 
0

使用array.reduce()总结的结果。例如:

$scope.totalOfSumAmount = $scope.items.reduce(function(carry, currentItem) { 
     //add the amount from the current item to the running total (carry) 
     return carry + currentItem.amount; 
    }, 0);//0 is the initial value 

这回叫功能(即在本例中function(carry, currentItem) {...)实际上可以接受四个参数:

  • 前值 - 从以前的迭代中值(或初始值)
  • 当前值 - 阵列中的当前元素
  • 当前索引 - 阵列中当前元素的当前索引
  • 原始数组 - ar射线我们遍历

和第二参数(可选)为初始值,因此,如果,例如,我们需要开始与10,我们可以传递,而不是0。

angular.module('app', []) 
 
    .controller('ctrl', function($scope) { 
 
    $scope.items = [{ 
 
     amount: 29.9, 
 
     code: "012", 
 
     currency: "BRL", 
 
     payedDate: "2016-11-10", 
 
     roDate: "2016-08-01", 
 
     type: "OTHER" 
 
    }, { 
 
     amount: 39.9, 
 
     code: "013", 
 
     currency: "BRL", 
 
     payedDate: "2016-11-11", 
 
     roDate: "2016-08-01", 
 
     type: "OTHER", 
 
    }]; 
 
    $scope.totalOfSumAmount = $scope.items.reduce(function(carry, currentItem) { 
 
     //add the amount from the current item to the running total (carry) 
 
     return carry + currentItem.amount; 
 
    }, 0);//0 is the initial value 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="ctrl"> 
 
Total: <span> {{ totalOfSumAmount }} </span> 
 
    </div>