1

Based in this example I need to sum the ages of the filtered users. It means, if I have three names filtered, the filter in the controller must to sum only these the ages.

html

<div data-ng-app="app" data-ng-controller="controller">
<input type="text" data-ng-model="parameter" placeholder="search">
 <p/>
 <table border="1">
 <thead>
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Age</th>
    </tr> 
<thead>
<tbody>
  <tr data-ng-repeat="user in users | filter: parameter">
    <td>{{$index+1}}</td>
    <td>{{user.name}}</td>
    <td>{{user.age}}</td>
  </tr>
 </tbody>
 <tfoot>
    <tr>
       <td colspan="2">Total ages</td>
       <td>{{users | sumByKey: 'age'}}</td>
    </tr>
 </tfoot>
 </table>
</div>

angularjs

var app = angular.module("app", []);

app.filter('sumByKey', function() {
    return function(data, key) {
        if (typeof(data) === 'undefined' || typeof(key) === 'undefined') {
            return 0;
    }

    var sum = 0;
    for (var i = data.length - 1; i >= 0; i--) {
       sum += parseInt(data[i][key]);
    }
    return sum;
    };
});

Any idea?

1 Answer 1

2

You could store the filtered data in a filteredList and pass it for the calculation,

<tbody>
      <tr data-ng-repeat="user in (filteredList = (users | filter: parameter))">
        <td>{{$index+1}}</td>
        <td>{{user.name}}</td>
        <td>{{user.age}}</td>
      </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="2">Total ages</td>
      <td>{{filteredList | sumByKey: 'age'  }}</td>
    </tr>
  </tfoot>

DEMO

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.