Reputation: 6278
I followed the following tutorial for adding two values in Angular; Addition of Two Numbers in AngularJS
But now I have to sum dynamic text box values inside ng-repeat.
I have the following Code
HTML Code
......
<table>
<tr>
<th>Name</th>
<th>Days</th>
</tr>
<tr ng-repeat="si in serImp">
<td>{{si.Name}}</td>
<td><input type="number" ng-model="si.Days" /></td>
</tr>
</table>
.......
<button ng-click="sum()">Calculate</button>
.......
JS code
.........
$scope.serImp = [];
$scope.serImp = data;
// here data is object contain multiple Name+Durations e.g.
/*data =
[0]
Name:"first"
Days: 1
[1]
Name:"second"
Days: 2
[2]
Name:"third"
Days: 3*/
$scope.sum = function () {
// sum code goes here
}
........
My Question is : How can I get the sum of the values/numbers from the ng-model="si.Days"
Upvotes: 1
Views: 989
Reputation: 136144
I will create function that will return all Days total & will directly bind to html
{{totalDays()}}
Code
$scope.totalDays = function(){
var totalDays = 0;
angular.forEach( $scope.serImp, function(si){
if(si.Days && !isNaN(si.Days)){
totalDays += Number(si.Days);
}
})
}
Upvotes: 1
Reputation: 23502
Use reduce to sum up all the days.
When you modify the values with ng-model you're manipulating the $scope.serImp
array. You can then use these values to calculate the sum.
$scope.sum = function () {
return $scope.serImp.reduce(function(prv, cur) {
return prv.Days + cur.Days;
});
}
Reduce takes an array and reduces it to one value by applying one function to all of its elements. In our case just simply adding up all the days.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Upvotes: 1