当用户在select中选择了一个值(声明数量并且默认值 1 )时, update()将触发并计算total_amount
我遇到的问题是,当我点击 addNewField()并创建了新输入时,为添加的字段输入了一个新值, total_amount 仅计算特定的索引字段,而不是总结所有索引字段。
JS档案
vm.update = function(index) {
vm.amount[index] = vm.quantity[index] * vm.selectedItem[index].price;
for(var i=0; i <= index; i++){
var sum = 0;
sum += parseInt(vm.amount[i]);
}
vm.total_amount = sum;
}
vm.addNewField = function(){
if(checkValue() == true){
var index = vm.fields.length;
vm.fields.push({'id': index });
vm.quantity[index] = 1;
}
}
HTML文件
<div class="row" ng-repeat="field in vm.fields track by $index">
<div class="form-group col-sm-8">
<label>Item Name</label>
<select ng-model="vm.selectedItem[$index]" ng-options="item as item.item_name for item in vm.items" ng-change="vm.update($index)" class="form-control">
</select>
</div>
<div class="col-sm-3">
<div class="form-group">
<label>Quantity</label>
<input type="number" class="form-control" ng-change="vm.update($index)" ng-model="vm.quantity[$index]" placeholder="123">
</div>
</div>
<div class="col-sm-1">
<div class="form-group">
<a ng-show="$index != '0'" href="" ng-click="vm.removeField($index)" class="button"><i class="fa fa-lg fa-trash"></i>
</a>
</div>
</div>
</div>
<div class="card-footer">
<button type="button" ng-click="vm.addNewField()" class="btn btn-sm btn-primary "><i class="fa fa-plus-circle"></i> Add Field</button>
</div>
<div class="row">
<div class="col-sm-6">
<label><strong>Total Amount:</strong></label>
</div>
<div class="col-sm-6" >
<label><strong>{{ vm.total_amount }}</strong></label>
</div>
</div>
答案 0 :(得分:1)
var sum = 0;
for(var i=0; i <= index; i++){
sum += parseInt(vm.amount[i]);
}
总和应该是外循环