我有一个带动态输入的动态表。每个输入都有一个唯一的编号,添加到模型名称的末尾。每个表有10个输入,最后一个是总数。我需要观察前9个输入并计算总和。以下是动态分配唯一模型名称后json的样子。
[
{
"section_id": 3155,
"subdivision_id": 3500,
"section_name": "Ph 1(P)-Mercedes",
"sectionInputs": [
{
"model": "price_min-3155"
},
{
"model": "price_max-3155"
},
{
"model": "units_occ-3155"
},
{
"model": "inv_mod-3155"
},
{
"model": "inv_fin-3155"
},
{
"model": "inv_vdl-3155"
},
{
"model": "inv_uc-3155"
},
{
"model": "inv_fut-3155"
},
{
"model": "inv_con-3155"
},
{
"model": "units_total-3155"
}
]
},
{
"section_id": 12863,
"subdivision_id": 3500,
"section_name": "Ph 1(P)-Adams",
"sectionInputs": [
{
"model": "price_min-12863"
},
{
"model": "price_max-12863"
},
{
"model": "units_occ-12863"
},
{
"model": "inv_mod-12863"
},
{
"model": "inv_fin-12863"
},
{
"model": "inv_vdl-12863"
},
{
"model": "inv_uc-12863"
},
{
"model": "inv_fut-12863"
},
{
"model": "inv_con-12863"
},
{
"model": "units_total-12863"
}
]
},
{
"section_id": 16152,
"subdivision_id": 3500,
"section_name": "Ph 1(P)-Unassigned",
"sectionInputs": [
{
"model": "price_min-16152"
},
{
"model": "price_max-16152"
},
{
"model": "units_occ-16152"
},
{
"model": "inv_mod-16152"
},
{
"model": "inv_fin-16152"
},
{
"model": "inv_vdl-16152"
},
{
"model": "inv_uc-16152"
},
{
"model": "inv_fut-16152"
},
{
"model": "inv_con-16152"
},
{
"model": "units_total-16152"
}
]
}
]
units_total
需要保存每个数组的总和值。我正在考虑使用watchgroup函数,但不确定如何使用for循环可以做到这一点?我对有关处理此问题的最佳方法的建议持开放态度。 javascript , jquery , lodash , linq.js 是当前在项目中使用的内容。
$scope.model = {};
function prepareDataForView() {
for (var i = 0; i < sections.length; i++) {
sections[i].sectionInputs = sectionInputSvc.sectionInputs(sections[i]);
sections[i].sectionInputLabels = sectionInputLabels;
}
$scope.sections = sections;
}
prepareDataForView();
答案 0 :(得分:1)
实现此目的的一种方法是在输入ng-change
时计算总数:
var sum = function(acc,cur){ return acc+cur; }
$scope.modelChanged = function(section, input){
var inputsCount = section.sectionInputs.length;
var totalInput = section.sectionInputs[inputsCount-1];
if(input === totalInput){
return;
}
var total = section.sectionInputs.slice(0, inputsCount - 1).map(function(input){
return $scope.model[input.model];
}).filter(angular.isDefined).reduce(sum, 0);
$scope.model[totalInput.model] = total;
};
然后可以在每个输入上调用:
<input ng-model="model[input.model]" ng-change="modelChanged(section, input)" type="number" />
答案 1 :(得分:1)
好吧,我已经用jQuery解决了这个问题,也许这个答案并不适合你,因为它与你的角度应用程序不一致,但我希望它对其他人有帮助。
$(document).on("change", "input", function()
{
$tr = $(this).parent().parent();
$tds = $tr.find("td");
var sum = 0;
$.each($tds, function(index, td){
var valueInput = $(td).find("input").val();
if(index < 9 ){
sum += parseFloat((valueInput != "") ? valueInput : 0 );
}
});
$tds.eq(9).find("input").val(sum);
});
以下是更新后的plunker