Beginning AngularJS

(WallPaper) #1
Chapter 4 ■ Filters and Modules

Creating a Custom Filter


At last, it’s time to look at creating a custom filter. Modules are great, but, while important, they’re probably not the
most exciting topic! This is perhaps because they don’t directly produce any visual output. However, custom filters are
more exciting, and we are going to use one to solve another issue that we have with our sample data.
For some unknown reason, some values sent back to us are dash delimited. The back end team has told us that
this is the way that the data is stored in the database and that it cannot change it. Nonetheless, we aren’t very keen on
presenting it to our end users in this format. The plan property is an example of this; it has a value of "super-basic-
plan". We could easily deal with one case of this without a filter, but we will assume it is a common problem, and we
will use a filter to solve it across the whole application.
I find that the best way to go about writing a filter is first to forget about filters. I get the logic working as regular
JavaScript, and then I tie it into a filter once I am satisfied. The requirement here is relatively simple: we want to
remove any dashes and replace them with spaces. Listing 4-11 shows a basic script that does just what we need.


Listing 4-11. A Simple Replace Dashes Function



This function is relatively straightforward. It accepts a single argument—the dash delimited string—and returns the
modified string. We have used a few calls to console.log for the purpose of verifying our expectation that it will strip out
all of the dashes and leave spaces in their place. The following output suggests this function is fit for this purpose:


super basic plan
something with a lot more dashes plan
noDashesPlan


■ Tip these days, it is increasingly common for Javascript programmers to write formal unit tests, but we won’t


explore that topic very much in this book. realistically, a few calls to the console.log method do not constitute proper


testing. as you have chosen to read a book about a framework that fully supports unit testing, i strongly recommend that


you read up on the topic in the near future.


As the function is working as we expect it to, we are now ready to convert it to an AngularJS filter. The method we use
to create an AngularJS filter is named, unsurprisingly, filter. It accepts two arguments: a name for the filter and a factory
function. We will name our filter 'stripDashes', and we will create a factory function that returns our stripDashes
function. That may have sounded a tad confusing, particularly the bit about factory functions. As usual, a code listing
should help clarify. Listing 4-12 is the filter method from Listing 4-9, revised to include the actual filter logic.

Free download pdf