Angular filter grouping with promise
Example demonstrating how to perform group filtering using Angular filters and a promise.
HTML
<script src="http://angular-ui.github.com/bootstrap/ui-bootstrap-tpls-0.1.0-SNAPSHOT.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<div ng-app="test" ng-controller="Main">
<div ng-repeat="team in teams| startFrom:(currentPage - 1)*pageSize | limitTo:pageSize "> <b>{{team}}</b>
<li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li>
</div>
<pagination rotate="true" num-pages="noOfPages" current-page="currentPage" max-size="maxSize" boundary-links="true"></pagination>
</div>
CSS
li {
margin-left: 1em;
}
JavaScript
var app = angular.module('test', ['ui.bootstrap']);
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: 'George',
team: 'team delta'
}, {
name: 'Steve',
team: 'team zeta'
}, {
name: 'Paula',
team: 'team eta'
}, {
name: 'George',
team: 'team teta'
}, {
name: 'Steve',
team: 'team iota'
}, {
name: 'Paula',
team: 'team kappa'
}, {
name: 'George',
team: 'team lambda'
}, {
name: 'Steve',
team: 'team zeta'
}, {
name: 'Paula',
team: 'team zeta'
}, {
name: 'George',
team: 'team beta'
}, {
name: 'Steve',
team: 'team omega'
}, {
name: 'Paula',
team: 'team beta'
}, {
name: 'Scruath of the 5th sector',
team: 'team gamma'
}];
// create a deferred object to be resolved later
var teamsDeferred = $q.defer();
// return a promise. The promise says, "I promise that I'll give you your
// data as soon as I have it (which is when I am resolved)".
$scope.teams = teamsDeferred.promise;
// create a list of unique teams
var uniqueTeams = unique($scope.players, 'team');
// resolve the deferred object with the unique teams
// this will trigger an update on the view
teamsDeferred.resolve(uniqueTeams);
// 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];
...