Reputation: 2893
I am creating a dynamic form fields in which there is only one input type number field inside the ng-repeat, user can add any number of fields by clicking add button, now I need to calculate the sum of values entered in dynamic number field and update in a text box, below I paste my code for your reference, help me to resolve
<fieldset ng-repeat="field in table.fields track by $index" >
<input type="number" ng-model="table.fields[$index].item_count" class="form-control" name="item_count" ng-pattern="/^[0-9]/" placeholder="Category Item View Count" required>
<button ng-click="removeChoice()" class="remove btn btn-danger" >close</button>
</fieldset>
<button class="addfields btn btn-success" ng-click="addFormField()" ng-disabled="!frm.cat_name.$dirty||!frm.cat_desc.$dirty||frm.cat_desc.$invalid||frm.cat_name.$inavalid">Add fields</button>
Upvotes: 1
Views: 2089
Reputation: 19060
Just create a custom filter to sum your numbers:
angular.module('App').filter('mysum', function() {
return function(items) {
var sum = 0;
items.forEach(function(item) {
if (item.item_count) {
sum += item.item_count;
}
})
return sum;
}
})
Then use it to display the sum:
<span>{{ table.fields | mysum }}</span>
Upvotes: 1