我在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]
,我该怎么做?
答案 0 :(得分:2)
您的代码中有一些错误。
首先,<span id="totalSum" ng-model="calculateSum()"></span>
- 此代码无效,此处您收到错误消息。
更好的方法是使用双向数据绑定按值输出:
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
之后,更好的方法是使用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 <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;
}