Mastering Web Application

(Rick Simeone) #1
Chapter 4
var input = [1, 2, 3, 4, 5, 6];

expect(paginationFilter(input, 0, 2)).toEqual([1, 2]);
expect(paginationFilter(input, 2, 2)).toEqual([5, 6]);
});

it('should return empty array for out-of bounds', function () {

var input = [1, 2];
expect(paginationFilter(input, 2, 2)).toEqual([]);
});
});

Testing a filter is as simple as testing a single function, and most of the time is really
straightforward. The structure of the sample test just presented should be easy
to follow as there are almost no new constructs here. The only thing that requires
explanation is the way of accessing instances of a filter from the JavaScript code.


Accessing filters from the JavaScript code


Filters are usually invoked from markup (using the pipe symbol in expressions), but
it is also possible to get access to filters instances from JavaScript code (controllers,
services, other filters, and so on). This way we can combine the existing filters to
provide a new functionality.


Filters can be injected to any objects managed by AngularJS Dependency Injection
system. We can express dependency on a filter using two distinct methods,
requiring either:



  • The $filter service

  • A filter name with the Filter suffix


The $filter service is a lookup function that allows us to retrieve an instance of a
filter based on its name. To see it in action we can write a filter that behaves similarly
to the limitTo one and can trim lengthy strings. Additionally our custom version
will add the "..." suffix if a string is trimmed. Here is the relevant code:


angular.module('trimFilter', [])
.filter('trim', function($filter){

var limitToFilter = $filter('limitTo');

return function(input, limit) {
if (input.length > limit) {
Free download pdf