我有一个功能,可以在点击时添加/删除新的输入字段。每个领域都有自己的ng-model fam.age。并且函数计算溢价,这取决于年龄。该函数的结果是一个像这样的对象数组:
[
{
"id":"fam1",
"age":2,
"btaccident":0.79,
"btdisability":0.13,
"btdeath":0.18,
"premium":5
},
{
"id":"fam2",
"age":3,
"btaccident":0.79,
"btdisability":0.13,
"btdeath":0.18,
"premium":5
}
]
对象数量取决于点击添加按钮的次数。
如何在VIEW中获得每个数组对象的“溢价”总和?
我曾尝试过休耕:
$scope.totalFamily = 0;
$scope.getTotalPremium = function () {
for (var i=0; i<$scope.familyMembers.length; i++) {
$scope.totalFamily += $scope.familyMembers[i].premium;
}
};
答案 0 :(得分:0)
您可以使用angular.forEach(),
$scope.sum = function(){
var total = 0;
angular.forEach($scope.data,function(key,value){
total+=key.premium;
})
return total;
}
<强>样本强>
var app= angular.module("MyApp", []);
app.controller("MyController", function($scope) {
$scope.data = [
{
"id":"fam1",
"age":2,
"btaccident":0.79,
"btdisability":0.13,
"btdeath":0.18,
"premium":5
},
{
"id":"fam2",
"age":3,
"btaccident":0.79,
"btdisability":0.13,
"btdeath":0.18,
"premium":5
}
];
$scope.sum = function(){
var total = 0;
angular.forEach($scope.data,function(key,value){
total+=key.premium;
})
return total;
}
});
&#13;
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
<h1> sum is : {{sum()}}</h1>
</body>
</html>
&#13;
答案 1 :(得分:0)
如果您没有使用像Underscore或Lodash这样的库,请使用forEach
maethod循环浏览对象。
var obj = [{"id":"fam1","age":2,"btaccident":0.79,"btdisability":0.13,"btdeath":0.18, "premium": 5},{"id":"fam2","age":3,"btaccident":0.79,"btdisability":0.13,"btdeath":0.18, "premium": 5}];
var sum = 0;
obj.forEach(function(val){sum = sum+val.premium})