Beginning AngularJS

(WallPaper) #1

Chapter 4 ■ Filters and Modules


Of course, two digits would be far better and much more in line with end users’ expectations. As it happens,
the number filter takes a single parameter, which lets you tell it how many decimal places to round a number to.
This raises a question: How do you pass parameters to a filter? Fortunately, it is very easy. You use a colon and then
enter the parameter value, as shown in the code snippet below.


Data used this quarter: {{ data.consumption | number:2 }} gigabytes


If you replace the paragraph in Listing 4-4 with the preceding snippet and load it into your browser, you will see
output identical to that in Figure 4-3.


Figure 4-3. Using parameters to control the behavior of a filter


As you can see, the number filter, indeed all filters, are quite easy to use. You can very easily change the format
of data without actually changing the underlying data source and without cluttering up the view or controller with
presentation-related code.
If you are working with data in which pinpoint accuracy is required, you should be very careful when you are
performing rounding operations. Due to the way in which computers represent numbers internally, results are not
always totally accurate. A discussion of floating-point-number precision is a little out of scope here, but you can use
your favorite search engine to learn more, if this is something that might be important to you.


The Date Filter

The date filter is indispensable and extremely flexible. Consider the dateJoined property of our sample data. It has
a value which, depending on the time when you view it, looks something like this: 2010-03-22T13:00:00.000Z. You
certainly don’t want to be showing it to end users in this format!


■ Tip don’t be fooled by the name. the date filter not only works with dates but also with times.


The date filter’s flexibility is due, in part, to the large number of format parameters you can pass to it and how
these can be combined to arrive at nearly unlimited ways of displaying dates and times (or portions of dates and
times). Table 4-1 and Table 4-2 show the available parameters. Look over these parameters, and then we will review a
code listing that shows some of the commonly used ones in action.

Free download pdf