What's a filter? At its most basic it's a function that takes multiple inputs and gives you one output. Typically a filter outputs primitives, less typically arrays, and rarely objects. I suppose they could output functions too (as an exercise to the reader, please ascertain that use case). They're a way to execute logic against a model or models that only the view cares about. For instance, you may be working with a number as an integer in the controller, but when it hits the view, it needs to be displayed formatted (like 9,000). This of course is nothing the controller should be concerned with, and for this, you would use a filter (the built-in number
filter, to be precise).
Let's add a filter to our blog application. Here's something trivial that you can do with CSS, but if you don't want to for some reason, you can use a filter:
// capitalizes the first letter of a string
blog.filter('capitalize', function () {
return function (s) {
if (!s || !angular.isString(s)) {
return s;
}
return s.charAt(0).toUpperCase() + s.substring(1);
};
});
Now if we have something in the view that needs capitalizing, just write {{something|capitalize}}
; problem solved. You'll notice that we evaluate the truthiness of s and its stringness; if we're passed an empty string or a non-string we'll just do nothing and return what we were passed. I like this pattern of writing filters, but others may disagree.
A filter is very simple and is most useful within the view. You can get at any filter via the $filter
service anywhere you can inject it, but the syntax can look a little strange:
// $filter was injected somewhere
var filtered_array = $filter('filter')(unfiltered_array, function some_function() { .. });
Still, this is a small price to pay for having them all at your fingertips. Let's write a trivial filter that takes an extra parameter and returns something (that is about as complex as filters get):
some_module.filter('myFilter', function() {
return function(a, b, c) {
return a + b + c;
};
});
And used in the view:
<h1>Hi, I Like Dinosaurs. I have {{male_dino_count|myFilter:female_dino_count:dino_egg_count}} of them in this paper bag.</h1>
The way it works is that parameter a
is the expression on the left side of the |
, the filter name is immediately after the |
, and parameter b
is the expression after the first :
, and parameter c
is the expression after the second:
The above is obviously a drawing of a bag full of male and female dinosaur eggs.
Filters can accept any type of parameter, but most commonly they are used on strings and arrays. This example above works on strings (numbers, even), but we can just as easily modify an array with one:
some_module.filter('myArrayTakingFilter', function() {
return function(a) {
return a.slice(0, 3) + '...' + a.slice(-3);
};
});
This just takes an array and returns a new array with the first and last three items of the original array, separated by an ellipsis. This might be handy if you have to display an array and have limited on-screen space for it.
Here's an example of unit testing a filter, using our blog application's filter as an example:
describe('Blog Filters', function () {
var $filter;
beforeEach(inject(function ($$filter) {
$filter = $$filter;
}));
describe('the capitalize filter', function () {
it('should capitalize a string, naturally', function () {
var capitalize = $filter('capitalize');
expect(capitalize('foo')).toBe('Foo');
});
});
});
A filter is a (hopefully) simple function that takes a model a view has, and makes it a little easier for the view to digest the model, or otherwise alters the appearance of the model. Filters are meant to be superficial and should probably not have side effects. They can be used outside of the context of a view, though this is less typical. You want to write a filter when you find you're massaging data in a controller, just for the sake of a view. Keep in mind though that filters get executed often, and for performance reasons it's best to keep them simple. Also, your filters are meant to simply munge data in the view--don't write filters that have side-effects!
So far during the course of this book we've talked AngularJS theory--now let's get on to applied science in the next chapter.
There has been error in communication with Booktype server. Not sure right now where is the problem.
You should refresh this page.