Mastering Web Application

(Rick Simeone) #1

Displaying and Formatting Data


return limitToFilter(input, limit-3) + '...';
}
return input;
};
});

The $filter('limitTo')function call allows us to get a hand on a filter instance
based on the filter's name.


While the previous method certainly works there is an alternative one that is often
faster to code and easier to read:


.filter('trim', function(limitToFilter){

return function(input, limit) {
if (input.length > limit) {
return limitToFilter(input, limit-3) + '...';
}
return input;
};
});

In the second example, presented here it is enough to declare a dependency named
as [filter name]Filter where the [filter name] is a name of a filter we want
to retrieve.


Accessing filter instances using the $filter service results in an odd
syntax, and this is why we find it easier to work with the form using
the Filter suffix. The only occasions where the $filter service
might be more convenient is when we need to retrieve several filter
instances in one place or retrieve a filter instance based on a variable,
for example, $filter(filterName).

Filters dos and don'ts


Filters do a marvelous job when used to format and transform data invoked from a
template offering nice and concise syntax. But filters are just a tool for a specific job
and can as any other tools cause damage if used incorrectly. This section describes
situations where filters should be avoided and an alternative solution would be a
better fit.

Free download pdf