gpt4 book ai didi

javascript - 从在 angularJs 中动态创建的输入中查找总数

转载 作者:行者123 更新时间:2023-11-30 17:00:38 26 4
gpt4 key购买 nike

我正在 angularJs 中动态创建一组输入元素。我想找到总数, Controller ,

     $scope.itemElements = [
{
"item": "item1",
"quantity": 2,
"rate": 12.5
},
{
"item": "item2",
"quantity": 2,
"rate": 12.5
},
{
"item": "item3",
"quantity": 2,
"rate": 12.5
}
];
$scope.calculateSum = function ()
{
var sum = 0;
for (var i = 0; i < $scope.itemElements.length; i++)
{
sum += $scope.itemElements["quantity"];
}

return sum;
}

HTML,

 <tr ng-repeat="itemElemen in itemElements">
<td><input type="text" class="form-control" ng-model="itemElemen.item" placeholder="Enter item" list="clientList"/></td>
<td><input type="text" class="form-control" ng-model="itemElemen.quantity" placeholder="Quantity"/></td>
<td><input type="text" class="form-control" ng-model="itemElemen.rate" placeholder="Rate"/></td>
<td><input type="text" class="form-control" placeholder="Amount" ng-value="itemElemen.quantity*itemElemen.rate"/></td>
</tr>

总计,

 Total &nbsp;<span id="totalSum" ng-model="calculateSum()"></span>

它不工作,得到错误是 [ngModel:nonassign],我该怎么做?

最佳答案

您的代码中有一些错误。

起初,<span id="totalSum" ng-model="calculateSum()"></span> - 此代码无效,此处出现错误。更好的方法是使用 2-way-data-binding 按值输出:

Total &nbsp;<span id="totalSum">{{calculateSum()}}</span>

之后,在你的函数中 calculateSum()你有错误

  $scope.calculateSum = function ()
{
var sum = 0;
for (var i = 0; i < $scope.itemElements.length; i++)
{
sum += $scope.itemElements[i]["quantity"];
// ^
// Here
}
return sum;
}

您需要引用数组中的元素 $scope.itemElements

之后,更好的方法是使用 input:number而不是 input:text对于您真正知道的模型是 Number

最后,input对于 Amount最好是 disabled .

最后,获取下一个代码。
HTML:

<table>
<tr ng-repeat="itemElemen in itemElements">
<td><input type="text" class="form-control" ng-model="itemElemen.item" placeholder="Enter item" list="clientList"/></td>
<td><input type="number" class="form-control" ng-model="itemElemen.quantity" placeholder="Quantity"/></td>
<td><input type="number" class="form-control" ng-model="itemElemen.rate" placeholder="Rate"/></td>
<td><input type="number" disabled class="form-control" placeholder="Amount" ng-value="itemElemen.quantity*itemElemen.rate"/></td>
</tr>
</table>
Total &nbsp;<span id="totalSum">{{calculateSum()}}</span>

JS:

  $scope.itemElements = [
{
"item": "item1",
"quantity": 2,
"rate": 12.5
},
{
"item": "item2",
"quantity": 2,
"rate": 12.5
},
{
"item": "item3",
"quantity": 2,
"rate": 12.5
}
];

$scope.calculateSum = function ()
{
var sum = 0;
for (var i = 0; i < $scope.itemElements.length; i++)
{
sum += $scope.itemElements[i]["quantity"];
}
return sum;
}

演示:http://plnkr.co/edit/k2zrbNcMXwPhNcflV3yF?p=preview

关于javascript - 从在 angularJs 中动态创建的输入中查找总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28942984/

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