Last active
August 29, 2015 14:09
-
-
Save repejota/56919e999f65c9113beb to your computer and use it in GitHub Desktop.
A simple sumByKey filter for AngularJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body> | |
<div class="container" ng-controller="TestCrtl"> | |
<h1>AngularJS array sum by field/key filter example</h1> | |
<table class="table table-bordered table-condensed"> | |
<thead> | |
<tr> | |
<th>Name</th> | |
<th>Posts</th> | |
<th>Comments</th> | |
</tr> | |
</thead> | |
<tbody> | |
<tr ng-repeat="user in users"> | |
<td>{{user.name}}</td> | |
<td>{{user.posts}}</td> | |
<td>{{user.comments}}</td> | |
</tr> | |
</tbody> | |
<tfoot> | |
<tr> | |
<th></th> | |
<th>{{users|sumByKey:'posts'}}</th> | |
<th>{{users|sumByKey:'comments'}}</th> | |
</tr> | |
</tfoot> | |
</table> | |
</div> | |
</body> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('exampleFilter', []) | |
.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; | |
}; | |
}) | |
.controller('TestCrtl', function ($scope) { | |
$scope.users = [{ | |
name: 'Kenny', | |
posts: 1, | |
comments: 6 | |
}, { | |
name: 'Kyle', | |
posts: 2, | |
comments: 7 | |
}, { | |
name: 'Eric', | |
posts: 3, | |
comments: 8 | |
}, { | |
name: 'Stan', | |
posts: 4, | |
comments: 9 | |
}, { | |
name: 'Butters', | |
posts: 5, | |
comments: 10 | |
}, ]; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment