Displaying and Formatting Data
To get the idea of an interface for the new filter; let's call it pagination we will write
a sketch of markup first:
<tr ng-repeat="item in filteredBacklog = (backlog |
pagination:pageNo:pageSize">
<td>{{item.name}}</td>
...
The new pagination filter needs to take two parameters: page to be displayed (its
index) and its size (number of items per page).
What follows is the very first, naive implementation of the filter (error handling was
deliberately omitted to focus on filter writing mechanics):
angular.module('arrayFilters', [])
.filter('pagination', function(){
return function(inputArray, selectedPage, pageSize) {
var start = selectedPage*pageSize;
return inputArray.slice(start, start + pageSize);
};
});
A filter, as any other provider, needs to be registered on an instance of a module.
The filter method should be called with a filter name and a factory function that
will create an instance of a new filter. The registered factory function must return
the actual filter function.
The first argument of pagination filtering function represents input to be filtered
while subsequent parameters can be declared to support filter options.
Filters are very easy to unit test; they work on a supplied input, and when done
properly they shouldn't have any side effects. Here is an example test for our custom
pagination filter:
describe('pagination filter', function () {
var paginationFilter;
beforeEach(module('arrayFilters'));
beforeEach(inject(function (_paginationFilter_) {
paginationFilter = _paginationFilter_;
}));
it('should return a slice of the input array', function () {