<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.1/angular-filter.js"></script>
<script src="script.js"></script>
<meta name="description" content="[groupBy and sum example]"/>
<meta charset="utf-8">
<title>angular-filter - groupBy and sum example</title>
</head>
<body>
<div ng-controller="MainController">
<ul ng-repeat="p in players | orderBy: 'team' ">
Group name: {{ p.team }}
<li ng-repeat="player in players | filter:p.team">
player: {{ player.name }}
</li>
<li>score: {{value | map: 'score' | sum}}</li>
</ul>
____________________________________
<ul ng-repeat="p in players | unique:'team' ">
Group name: {{ p.team }}
<li ng-repeat="player in players | filter:p.team">
player: {{ player.name }}
</li>
<li>score: {{value | map: 'score' | sum}}</li>
</ul>
</div>
</body>
</html>
// Code goes here
angular.module('app',['angular.filter'])
.filter('unique', function() {
// Take in the collection and which field
// should be unique
// We assume an array of objects here
// NOTE: We are skipping any object which
// contains a duplicated value for that
// particular key. Make sure this is what
// you want!
return function (arr, targetField) {
var values = [],
i,
unique,
l = arr.length,
results = [],
obj;
// Iterate over all objects in the array
// and collect all unique values
for( i = 0; i < arr.length; i++ ) {
obj = arr[i];
// check for uniqueness
unique = true;
for( v = 0; v < values.length; v++ ){
if( obj[targetField] == values[v] ){
unique = false;
}
}
// If this is indeed unique, add its
// value to our values and push
// it onto the returned array
if( unique ){
values.push( obj[targetField] );
results.push( obj );
}
}
return results;
};
})
.controller('MainController', function($scope) {
$scope.players = [
{name: 'Gene', team: 'alpha', score: 10},
{name: 'George', team: 'beta', score: 14},
{name: 'Steve', team: 'gamma', score: 8},
{name: 'Paula', team: 'beta', score: 28},
{name: 'Scruath', team: 'gamma', score: 7}
];
});
/* Styles go here */
angular-filter - groupBy and sum example