Angular Custom Filters

Objectives

  • Review the concept of filters in Angular

  • Create a custom filter and utilize it in an app

Review of Filters

Angular uses the concept of filters to easily process data before output. Filters can work on any type of data (strings, numbers, arrays, etc). There are a bunch of built-in filters and we can easily create our own.

Basic Filter Example

{{myVar | lowercase}}

Outputs the value of myVar in to the lowercase filter which outputs the string as lowercase.

Filter options

Some filters also take in optional parameters. Angular uses colons (:) to separate arguments for filters.

Filter Arguments Example

//in controller
$scope.someNumber = 12345;


//in view
{{someNumber | currency}}
// Outputs: '$12,345.00'

{{someNumber | currency : '£'}}
// Outputs: '£12,345.00'

{{someNumber | currency : '£' : 4}}
// Outputs: '£12,345.0000'

Each filter has it's own set of options. See the full list of built-in filters for more details.

Chaining filters

Filters can be chained together just like terminal commands. The output of each filter will feed into the next filter.

In this example we'll use a filter called limitTo which limits the length of a string or array.

Example

Custom Filters

Creating a custom filter is fairly simple, but the syntax is a little foreign at first. Let's create a filter called reverse that takes a word and prints it in reverse.

Example

A filter is created by using the filter method, and like the other angular methods, the first parameter is the name of the filter we want to create. The second parameter is a function that returns another function.

This inner function is the actual filter that is triggered using the same syntax as the built-in filters.

The first parameter of the inner function is the actual data that was piped in to the filter. Every subsequent parameter come from things separated by colons (again like in the built-in filters).

Usage Example

This would trigger the inner function and set input to the value of someVar and preserveWords to true. Additional, parameters can be added in the same fashion.

Complete filter example

The below filter will take in a word and output it reversed. If preserveWords is set to true, it will keep the words intact.

Custom Filter

Usage Example

More info: Angular Docs - Filters

Exercises

nth

Create a filter called 'nth' that accepts a number and adds the proper suffix to it, like 1st, 2nd, 3rd, 4th and so on. Zero should show as 0th.

Sample input:

Sample output:

pluralize

Assume you have an array of objects. Create a filter called 'pluralize' that accepts accepts a list length as an input and accepts two other parameters:

  • length - a number representing a quantity

  • singular - a string to show if the length is 1

  • plural - a string to show if the length is not 1

The filter should return the singular string if the input length is exactly equal to one. Otherwise, it should return the plural string.

The plural string is an optional parameter. Detect if it is passed to the filter. If plural is not passed to the filter then append the letter "s" to the singular string.

The filter should output the following text to the page for different input:

filesize

Create a filter called filesize that accepts a number representing the number of kilobytes in a file and returns a string with a human-readable size description in the following units:

  • bytes

  • KB - kilobytes (1024 bytes)

  • MB - megabytes (1024 kilobytes)

  • GB - gigabytes (1024 megabytes)

The filter should accept an optional parameter precision that defaults to 2 that represents how many digits to show after the decimal place if the filesize if larger than one megabyte. Refer to MDN toFixed() documentation for details.

The filter should output the following list on the page:

primes

Create filter called primes that accepts a list of numbers and returns a new list containing only prime numbers:

The filter should output the following list on the page:

ago

Create a filter called ago that accepts a timestamp string and returns a string representing how long ago the timestamp occurred.

The filter should support time units of years, months, days, hours, seconds and anything occuring less than 3 seconds ago should just say 'moments ago.'

Notice the sample output properly pluralizes "1 year ago" and "2 years ago." It's possible to use filters outside of views! Search the internet to find out how to call one filter from inside another filter.

Use the Date object to perform date calculations. MDN has great documentation about what methods are available on instances of the Date object. (Note: be sure to notice that the getYear() method was deprecated because of the Y2K bug!)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear

Here's some sample input:

Here's some sample output. Beware, time is fickle and your actual results may vary:

Last updated

Was this helpful?