我正在尝试创建一个对象,其中键是年数,值是金额
vm.argiterraYearlyLocalCost = {"2016":0,"2017":0,"2018":0,"2019":0} //year(key):amount(value)
我在视图中有一个输入字段,可以让我创建新的金额,每当我添加不同的addLocalCostContributor时,它会检查条件是否匹配,金额将被添加到年份。
function addLocalCostContributor(localCost, year) {
localCost.contributors.push({});
for(var i=0; i < localCost.contributors.length;i++ ) {
if(angular.isDefined(localCost.contributors[i].contributor) && localCost.contributors[i].contributor.name ==='Agriterra') {
var amount = parseInt(localCost.contributors[i].amount);
vm.argiterraYearlyLocalCost[year] = parseInt(vm.argiterraYearlyLocalCost[year] || 0) + amount;
}
}
}
vm.argiterraYearlyLocalCost = {};//ths is intiliased in the top of angular controller
问题是,无论何时添加新金额并满足条件,金额都会增加,但它会重新开始循环。例如,我添加了firstAmount,它给了我{'2016':firstAmount},但是当我添加newAmount并提交它再次启动循环并且它给出{'2016':firstAmount + firstAmount + newAmount},而我想要的只是firstAmount + newAmount。如果我可以在每次提交时重置vm.argiterraYearlyLocalCost[year]
(并且函数循环以增加属性),我将得到正确的答案。
如果有人可以从不同的眼睛看到,我无法清楚地想清楚如何以及在何处重置此属性。
答案 0 :(得分:2)
尝试在for
循环运行之前重置该年份的金额。
function addLocalCostContributor(localCost, year) {
localCost.contributors.push({});
vm.argiterraYearlyLocalCost[year] = 0; // <= added this line
for (var i = 0; i < localCost.contributors.length; i++) {
if (angular.isDefined(localCost.contributors[i].contributor)
&& localCost.contributors[i].contributor.name === 'Agriterra') {
var amount = parseInt(localCost.contributors[i].amount);
vm.argiterraYearlyLocalCost[year] = parseInt(vm.argiterraYearlyLocalCost[year] || 0) + amount;
}
}
}
vm.argiterraYearlyLocalCost = {};