This page looks best with JavaScript enabled

How to create and use filters in AngularJS

 ·  โ˜• 2 min read  ·  โœ๏ธ Adesh

Overview

AngularJS filters are used to format the data. There are different types of AngularJS filters. These are:

  • uppercase: format a string to upper case.
  • currency: format a number to a currency
  • filter: select a subset of items from an array
  • date: date formatting filter
  • json: format an object to a json string
  • lowercase: convert string to lowercase
  • number: convert string to number
  • orderBy: sort an array by an expression

These are the AngularJS built-in filters. These can be used in several places of your application like in views template, controllers or services.

AngularJS filters are used as a โ€˜|โ€™ pipe character with an expression. You can define your own filters, which is called Custom filters.

Filter Usage

Here are some examples about how to user different filter.

uppercase Filter

Output:

Your first name is ADESH

Currency Filter

Output:

Total price is : $50.00

Filter Filter

This filter is used only with an array, and we are using the orderBy filter here to sort the country name.

Output:

Looping with objects:

  • Denis, Canada
  • Ruby, China
  • Mary, England
  • Jordan, Norway
  • John, Russia
  • Thomas, Sweden
  • Adesh, USA

lowercaseย Filter

Output:

Your last name is adesh

Custom Filters

In addition to AngularJS filters, we can create our own filter. It is very easy to create your own custom filter. You have to register your filter with the application module. We are going to create our custom filter named myCustomFilter. Letโ€™s take a look at below code.

Output:

My Custom Filter

Summary

In this blog, we learned about how to create and use different types of filters in AngularJS application. We also learned about our custom filter and used them in our view template and in our controller. Filters are great way to format application data.

Cheers!

Read more:

http://codetalkie.com/2018/10/14/the-power-of-directives-in-angularjs/

Introduction to Module and Directives in AngularJS

Factory and Services in AngularJS

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect