Reputation:
im trying to do sum operation on my table Like
Item Price
abc 10
xyz 20
Ites=>2 Price=>30
For this i wrote simple custome filter
.filter('SumOfAmt', function () {
return function (data, key) {
if (angular.isUndefined(data) || angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data, function (value) {
sum = sum + parseInt(value[key]);
Html code
<form name="form1" ng-submit="SaveDb(form1.$valid)" novalidate>
<b>cost</b><input type="number" ng-model="cost" required />
</form>
This is my Table when user enter in form it display in table
<table class="table table-bordered">
<tr>
<td>Name</td>
<td>Price</td>
</tr>
<tr ng-repeat="Emp in EmployeeList">
<td>{{Emp.EmpName}}</td>
<td>{{Emp.Cost | currency}}</td>
</tr>
This is {{EmployeeList|SumOfAmt:'Cost'}}
</table>
Upvotes: 2
Views: 189
Reputation: 7326
And what's wrong?
With your custom filter you can get the right sum, you just need to return sum:
.filter('SumOfAmt', function () {
return function (data, key) {
if (angular.isUndefined(data) || angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data, function (value) {
sum = sum + parseInt(value[key]);
});
return sum;
};
});
But another alternative is:
.filter('SumOfAmt', function () {
return function (data, key) {
if (angular.isUndefined(data) || angular.isUndefined(key))
return 0;
return data.map(function(a){return parseInt(a[key])}).reduce((a, b) => a + b, 0);
};
});
Upvotes: 1