AngularJS Filter – Built-in, Custom and Stateful Filters With Examples

Free Angular course with real-time projects Start Now!!

Have you heard the term AngularJS filter? This article is specially dedicated to filters in AngularJS: What is a filter, how and when to use filters with an example. Along with this, we will learn built-in filters and custom filters in AngularJS.

So, let’s get familiar with the new tool – AngularJS Filter.

AngularJS Filters Tutorial

What is AngularJS Filter?

AngularJS filter is a tool, which we can use to format the data. With this filter, the user can see and modify according to the requirement. It is added in angular to format the data that is being displayed on the view part.

Syntax of Filter

With pipe character (|), we can add filters in angularJS.

Filters can club with the expression as well as a directive.

Syntax:

{{expression| name_of_filter}}

Example: {{name | uppercase}}

Here, a name is the expression and uppercase is the built-in filter provided by angular. It converts the name in uppercase in view part.

Recommended Reading – What is ng-view in AngularJS?

When to use a filter in AngularJS?

When we want to display the data in view part in a particular format in that scenario we can use AngularJS filter. We can display the data in the uppercase format, lowercase format etc. In whatever format, we entered the text but it can easily get displayed in any format by angular as per the type of filter used. AngularJS Filters can change the way of displaying the output.

AngularJS Filter in View Template

Filters are applied on expression to refrain the input. We can apply the AngualrJS Filter in a view template. Also, we can apply a filter on the result obtained by another filter. Chaining is the phenomenon when filters are applied to the already filtered content.

Syntax:

{{ expression | filter1 | filter2 | ... }}

AngularJS Filters have arguments.

Syntax:

{{ expression | filter:argument1:argument2:... }}

When will filter get execute

Whenever the inputs have changed in the template, the filter gets to execute.

Do you know How MVC works in AngualrJS?

Types of Built-In Filters in AngularJS

These are the following built-in filters, let’s discuss them one by one:

Types of Built-in filters in AngularJS

1. Uppercase

Uppercase Filter use to convert the string into an uppercase string.

If Uppercase filter is used then the string that is taken as an input in any format is formatted and gets displayed to the user in an uppercase format as an output.

Syntax:

{{expression | uppercase}}

Example:

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
<h1>AngularJS Uppercase Filter: </h1>
<div ng-init="firstName='data'; lastName='flair'">
Upper case: {{firstName + ' ' +lastName | uppercase}} </div>
</body>
</html>

Output:

AngularJS Uppercase Filter:

Upper case: DATA FLAIR

2. Lowercase

Lowercase Filter in AngularJS uses to convert the string into a lowercase string.

If a lowercase filter is used then the string that is taken as an input in any format is formatted and gets displayed to the user in the lowercase format as an output.

Syntax:

{{expression | lowercase}}

Also, see – List of major Directives for Angular HTML DOM 

Example:

<!DOCTYPE html>
<html>
<head>
<script>
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
<h1>AngularJS Lowercase Filter: </h1>
<div ng-init="firstName='DaTa'; lastName='FlaiR'">
Upper case: {{firstName + ' ' +lastName | lowercase}} </div>
</body>
</html>

Output:

AngularJS Lowercase Filter:

Lower case: data flair

3. Currency

Currency filter is used to change the convert the number in the specified currency. In case no symbol of currency is specified then by default the symbol for current locale is used.

Syntax:

{{expression | currency : 'currency_symbol' : 'fraction'}}

Example:

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
Enter Amount:<input type="number" ng-model= "price"><br>
The amount is: {{price | currency }}
</body>
</html>

Output:

Enter Amount: ​

The amount is:

When you enter text in the textbox the output will be

Enter Amount: ​8

The amount is: $8.00

4. Filter

It is applied only on array elements. A particular element is selected from an array based on certain condition and a new array is created from the existing array.

Syntax:

{{ expression | filter : filter_criteria }}

Have a Look – AngularJS Dependency Injection with Its Components

Example:

<!DOCTYPE html> 
<html> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<body> 
<div ng-app="myApp" ng-controller="namesCtrl"> 
<ul> 
  <li ng-repeat="x in names | filter : 'i'"> 
     {{ x }} 
  </li> 
</ul> 
</div> 
<script> 
angular.module('myApp', []).controller('namesCtrl', function($scope) { 
   $scope.names = [ 

'Oshin', 
'Iram', 
'Karan', 
'Jay', 
'Anand' 
   ]; 
 }); 
  </script> 
  <p>The names containing the letter "i".</p> 
  </body> 
</html>

Output:

Oshin

Iram

The names containing the letter “i”.

5. Orderby

It is used to sort the data either in ascending or in descending order.

Syntax:

{{ expression | orderBy : predicate_expression : reverse}}

6. Date

Date filter in AngularJS use to convert the date into a string according to the specified date format.

Syntax:

{{date_expression | date : 'format'}}

The various formats are:

YYYY,MM,DD,D etc

Example:

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app>
<div ng-init="Date = 423234234888 ">
Default date: {{Date| date}} <br />
Year: {{Date | date:'yyyy'}} <br />
</div>
</body>
</html>

Output:

Default date: May 31, 1983

Year:1983

Follow this link to know the Best way to include HTML Code in File in AngularJS?

7. Number

It is used to format the data or a numerical value taken as an input. It can add a comma or specified fraction size in it. In case the number expression doesn’t contain valid numeric data in that case number filter display an empty string.

Syntax: 

{{ number_expression | number:fractionSize}}

Example 

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
<h1>AngularJS Number Filter Demo: </h1>
Enter Price: <input type="number" ng-model="Price" /> <br />
100000 | number = {{100000 | number}} <br />
Price | number = {{Price | number}} <br />
Price | number:3 = {{Price | number:3}} <br />
Price | number = <span ng-bind="Price | number"></span>
</body>
</html>

Output:

AngularJS Number Filter Demo:

Enter Price: ​

100 | number =

Price | number =

Price | number:3 =

Price | number =

When you enter a value in the text field then the output will be

AngularJS Number Filter Demo:

Enter Price: ​8

100 | number = 100

Price | number = 8

Price | number:3 = 8.000

Price | number = 8

Custom Filters in AngularJS

Angular JS provides a way to create our own filter that is customized filter. You can create one by registering a filter factory function in a module. AngularJS Filter function should be a pure function. Pure function means the same result is produced as per the given input. Also, it should not affect an external state.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-filter-reverse-production</title>
  <script src="//code.angularjs.org/1.7.7/angular.min.js"> 
  </script>
  <script src="script.js"></script> 
</head>
<body ng-app="ReverseFilter">
  <div ng-controller="ReverseController">
  <input ng-model="msg" type="text"><br>
Content with No filter: {{msg}}<br>
Content after Reverse filter: {{msg|reverse}}<br>
Content after Reverse Filter in uppercase: {{msg|reverse:true}}<br>

</div>
</body>
<script>
(function(angular) {
  'use strict';
angular.module('ReverseFilter', [])
  .filter('reverse', function() {
  return function(input, uppercase) {
  input = input || '';
  var out = '';
  for (var x = 0; x < input.length; x++) {
   out = input.charAt(x) + out;
   }
   // conditional based on optional argument
   if (uppercase) {
     out = out.toUpperCase();
    }
    return out;
  };
})
    .controller('ReverseController', ['$scope', 'reverseFilter', function($scope, reverseFilter) {
  $scope.msg = 'angular';
  $scope.filteredMessage = reverseFilter($scope.msg);
 }]);
})(window.angular);

</script>
</html>

Output:

Angular

Content with No filter: Angular

Content after Reverse filter: ralugnA

Content after reverse filter in uppercase: RALUNGA

Let’s create AngularJS Modules and explore its different types

Testing of Custom Filters

Like any other code, we can check filtered code also. Before Each(module(‘core’)) loads the core module into the injector. Core module contains the checkmark filter.

describe('checkmark', function() {

 beforeEach(module('core'));

 it('should convert boolean values to unicode checkmark or cross',
   inject(function(checkmarkFilter) {
     expect(checkmarkFilter(true)).toBe('\u2713');
     expect(checkmarkFilter(false)).toBe('\u2718');
   })
 );
});

AngularJS Filters in Controller, Directive, and Services

We can use AngularJS Filter inside the components like directives, controller and services.

To implement this you have to inject <filtername>Filter into your component.

Like in below example, we can inject the filterFilter to implement this. The injected argument is a function with two parameters. The first argument is the value that needs to be a formatted and the second argument is the filter parameters starting with.

Let’s see this with an example

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-filter-in-controller-production</title>

  <script src="//code.angularjs.org/1.7.7/angular.min.js"></script>
  <script src="script.js"></script>

</head>
<body ng-app="FilterModule">
  <div ng-controller="FilterinController as ctrl">
  <div>
    All entries:
    <span ng-repeat="entry in ctrl.array">{{entry.name}} </span>
</div>
<div>
  Entries that contain "j":
  <span ng-repeat="entry in ctrl.filteredArr">{{entry.name}} 
 </span>
</div>
</div>
</body>
<script>
(function(angular) {
 'use strict';
angular.module('FilterModule', []).
  controller('FilterinController', ['filterFilter', function FilterController(filterFilter) {
 this.array = [
    {name: 'Kethy'},
    {name: 'Jerry'},
    {name: 'Brian'},
    {name: 'John'},
    {name: 'Bruno'}
  ];
  this.filteredArr = filterFilter(this.array, 'j');
 }]);
})(window.angular);
</script>
</html>

Output:

All entries: Kethy Jerry Brian John Bruno

Entries that contain “j”: Jerry John

Follow this link to revise Controller in AngularJS with Syntax and Examples

Stateful Filter

It is discouraged to write stateful filters because angularJS cannot optimize its execution. Rather than writing a stateful filter, you can mark a filter as stateful. By marking a filter as stateful, during each digest cycle filter can execute one or more time.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-filter-stateful-production</title>

  <script src="//code.angularjs.org/1.7.7/angular.min.js"> 
  </script>
  <script src="script.js"></script>
</head>
 <body ng-app="StatefulFilter">
   <div ng-controller="StatefulController">

  No filter: {{msg}}<br>
  Decorated: {{msg | decorate}}<br>
</div>
</body>
<script>
(function(angular) {
  'use strict';
angular.module('StatefulFilter', [])
 .filter('decorate', ['decoration', function(decoration) {

  function decorateaFilter(input) {
   return decoration.symbol + input + decoration.symbol;
  }
  decorateaFilter.$stateful = true;

  return decorateaFilter;
 }])
     .controller('StatefulController', ['$scope', 'decoration', 
function($scope, decoration) {
   $scope.msg = 'angular';
   $scope.decoration = decoration;
 }])
  .value('decoration', {symbol: '*'});
})(window.angular);
</script>
</html>

Output:

No Filter: Angular

Decorated: *angular*

Summary

Therefore from the above article, we can conclude that filters are the built-in services in angular. Which we can use to format the data. These data will gather as an input from a user and display to the user in view part in a filtered manner. There are various AngularJS filter is available to filter the data as discussed above such as upper, lower, currency, number etc.

Hope, you like this AngularJS Filter tutorial. You may also like to know 7 Built-in Directive in AngularJS

Still, have a doubt? Feel free to ask in the comment section.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *