Angular filter grouping with promise
Example demonstrating how to perform group filtering using Angular filters and a promise.
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<div ng-app="app" ng-controller="Main">
<div ng-repeat="team in teams">
<b>{{team}}</b>
<li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li>
</div>
</div>
CSS
li {
margin-left: 1em;
}
JavaScript
var app = angular.module('app', []);
app.controller('Main',
function Main($scope, $q) {
$scope.players = [{name: 'Gene', team: 'team alpha'},
{name: 'George', team: 'team beta'},
{name: 'Steve', team: 'team gamma'},
{name: 'Paula', team: 'team beta'},
{name: 'Scruath of the 5th sector', team: 'team gamma'}];
$scope.teams = unique($scope.players, 'team');
// function that takes an array of objects
// and returns an array of unique valued in the object
// array for a given key.
// this really belongs in a service, not the global window scope
function unique(data, key) {
var result = [];
for (var i = 0; i < data.length; i++) {
var value = data[i][key];
if (result.indexOf(value) == -1) {
result.push(value);
}
}
return result;
}
}
);