Beginning AngularJS

(WallPaper) #1

Chapter 4 ■ Filters and Modules


Listing 4-12. An Angular Filter Implementation


myAppModule.filter('stripDashes', function () {
// the function we are in returns
// the function below
return function(txt) {
return textToFilter.split('-').join(' ');
};


});


Of particular note here is the fact that the filter function does not itself implement our logic; rather, it returns
a function that implements it. This is why that second argument supplied to the filter method is called a “factory
function”; its main purpose in life is to manufacture functions. This can seem a little strange at first, but it is a common
design pattern (generally known as the factory pattern), and it’s certainly not difficult to implement. It might help if
you think about this from AngularJS’s point of view: we don’t want to use a function here and now, but we do want to
return a function to AngularJS, for it to utilize whenever we invoke the associated filter.
The argument we named txt represents the expression value that is passed in to this filter function when it is
used, that is, it’s the value we are filtering. In Listing 4-13, which uses our new custom filter, you can see that txt will
be the value of data.plan.


Listing 4-13. Trying Out the stripDashes Filter


<!DOCTYPE html>




Filter Demo




Plan type: {{data.plan}}


Plan type: {{data.plan | stripDashes}}




There you have it, a very handy filter that we can reuse across our application. As an additional example, let’s
create another filter. As I mentioned earlier in the chapter, we can improve upon the way we handle the firstName and
surname by using a technique known as title casing, instead of simply converting them to lowercase. We can do this by
making sure the first character is in uppercase and all of the remaining characters are in lowercase. As before, let’s first
write the code that will accomplish this, before we create the filter itself. Have a look at Listing 4-14.


Listing 4-14. A Basic Title Casing Function