2

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>
1
  • With the help of this library you can write {{EmployeeList | map : 'Cost' | sum}} Commented Nov 16, 2017 at 5:47

1 Answer 1

1

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);
    };
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.