Filters provide an easy way to format the view. In this post, we will explore in-built and custom filters in AngularJS.
Recently, I switched back to Angular (1.6x) after a brief stint at React due to work requirements and have been enjoying the transition quite a bit. OK, let’s get started!
Filters in AngularJS
Filters can be added in AngularJS to format data.
Thank you w3schools, it could not have been more self-referential. Angular provides a bunch of in-built filters to format data like currency and date among others. They can be used directly with the data binding expressions with the |
operator.
index.html
js/main.js
Here is what the DOM renders.
The currency filter uses $
by default but can be changed as needed.
Now that’s nifty. Angular can recognize the types and format accordingly.
The filter Filter
The filter filter can only be used on arrays, and it returns an array containing only the matching items.
Let’s add few cats to main.js
.
Now if we only want to display animals with an i
in their names, we can use filter
with the binding expression in index.html
.
And it will display only lion and tiger.
Custom Filters
In-built filters are good, but the custom ones are great! Angular allows us to create our own filters for arrays, objects and everything else.
Going back to our first example, assume that the gender is stored as a number.
- 1 for male
- 2 for female
- 3 for non-binary
And here is the modified ben
object.
To display 3
as the corresponding gender title, all we need is to declare a little function in main.js
.
We just created a custom filter gender
that can be used within the data binding expression.
And its expected result.