gpt4 book ai didi

javascript - 迭代多个 ng-model

转载 作者:行者123 更新时间:2023-12-03 12:22:47 26 4
gpt4 key购买 nike

我有一组 ng-model 元素,并且想要对所有值求和并显示它。我的套装看起来像这样

<div ng-app>
<div ng-controller="SumApp" >
<input ng-model='val1' type='number' ng-change='calculate()' ng-init='val1=0'/>
<input ng-model='val2' type='number' ng-change='calculate()' ng-init='val2=0'/>
<input ng-model='val3' type='number' ng-change='calculate()' ng-init='val3=0'/>
<input ng-model='val4' type='number' ng-change='calculate()' ng-init='val4=0'/>
<div>{{sum}}</div>
</div>
</div>

我的 Controller 看起来像这样

<script type="text/javascript">
function SumApp($scope) {
$scope.sum = 0;

$scope.calculate = function() {
$scope.sum = $scope.val1+$scope.val2+$scope.val3+$scope.val4
};
}
</script>

就像模型html一样动态生成

问题是是否有任何方法可以让我在 Controller 定义本身中不使用任何list的情况下迭代一组元素ng-model

最佳答案

随时了解输入的确切数量,您可以轻松地使用循环对它们进行求和:

$scope.sum = 0;
$scope.numInputs = 5;

$scope.calculate = function() {
var i;
$scope.sum = 0;

for(i = 0; i < $scope.numInputs; i++) {
$scope.sum += parseInt($scope['val' + i], 10);
}
};

关于javascript - 迭代多个 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24361112/

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