[英]Find total from inputs which are created by dynamically in angularJs
我正在angularJs中動態創建一組輸入元素。 我想找到總計,財務總監,
$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>
Totatl,
Total <span id="totalSum" ng-model="calculateSum()"></span>
它不起作用,得到的錯誤是[ngModel:nonassign]
,我該怎么做?
您的代碼中有一些錯誤。
首先, <span id="totalSum" ng-model="calculateSum()"></span>
-此代碼無效,此處會出現錯誤。 更好的方法是使用2路數據綁定按值輸出:
Total <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
元素
之后,更好的方法是對您真正知道是Number
的模型使用input:number
而不是input:text
最后,最好disabled
Amount
input
。
最后,獲取下一個代碼。
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 <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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.