Chapter 4 ■ Filters and Modules
Of course, the function is now a little more complicated. The trick to understanding it lies in the use of the string
object’s replace() method. This method is very powerful, but it does require some knowledge of regular expressions
before you can truly master it. A regular expression is a sequence of symbols and characters expressing a pattern to
be searched for within a longer piece of text. The first argument to this method is a regular expression, which looks
like this: /\w\S*/g. More specifically, in this particular case, it is looking for each individual word. The anonymous
function, which is the second argument, is executed for each word that is found. This function uses the same logic
you saw in Listing 4-12; therefore, each word now has its first character converted to uppercase and all remaining
characters converted to lower case.
Now we will use this approach to create another filter in the module we created in Listing 4-9. We will name this
one toTitleCase. This is shown in Listing 4-16.
Listing 4-16. An Angular Filter Implementation
myAppModule.filter("toTitleCase", function () {
return function (str) {
return str.replace(/\w\S*/g, function(txt){ return txt.charAt(0).toUpperCase() + txt.
substr(1).toLowerCase();});
};
});
With the filter in place, we can now make use of it. Listing 4-17 shows it in action. In this example, we show
the filter working on individual words (firstName and surname), and we also see it in action on a concatenation of
firstName and surname.
Listing 4-17. Using the toTitleCase Filter
<!DOCTYPE html>
First Name: {{data.firstName | toTitleCase}}
Surname: {{data.surname | toTitleCase}}
Full Name: {{ data.firstName + data.surname | toTitleCase}}
Summary
We looked at both filters and modules in this chapter, and you learned how they relate to each other. AngularJS ships
with some handy built-in filters, and you now know how to create your own. You can also benefit from filters that have
been made available online (such as those found at http://ngmodules.org/)..)
Modules gave us something to “attach” our filter to, and you also learned that modules are AngularJS’s preferred
mechanism for packaging and organizing code. We will take the module approach for the rest of the book, so there is
still plenty of time to see them in action, should the topic still seem a little hazy.