gpt4 book ai didi

javascript - 如何计算ng-repeat中动态命名模型名称的总和

转载 作者:行者123 更新时间:2023-11-30 16:21:08 26 4
gpt4 key购买 nike

我有一个带有动态输入的动态表。每个输入都有一个唯一的编号添加到模型名称的末尾。每个表有 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 是目前在项目中使用的。

这是 working plunker

 $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();

最佳答案

实现这一点的一种方法是在输入 ng-changes 时计算总数:

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" />

这是 an updated plunker .

关于javascript - 如何计算ng-repeat中动态命名模型名称的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com