wilson wilson - 1 month ago 14
AngularJS Question

AngularJS - Summing filtered rows in table

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?

Answer

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

Comments