AngularJS Filters & AngularJS Custom Filter with Example

โšก Smart Summary

A Filter in AngularJS formats the value of an expression for display without altering the underlying data. Built-in filters cover case, numbers, currency and JSON, while a custom filter handles any formatting rule the framework does not already provide.

  • ๐Ÿงพ Core Principle: A filter transforms only what the view displays; the value held on the scope object is never modified.
  • โž– Pipe Syntax: The vertical bar separates the expression from the filter name, and a colon passes an argument to it.
  • ๐Ÿ”ค Case Filters: lowercase and uppercase convert a string for display, and no capitalize filter exists in AngularJS.
  • ๐Ÿ”ข Number and Currency: number limits decimal places, while currency prefixes a locale-driven symbol to the value.
  • ๐Ÿ› ๏ธ Custom Filters: Registering a factory that returns a function creates a reusable filter available across the whole module.
  • โšก Purity Matters: A filter must return the same output for the same input, because AngularJS caches results and skips re-running pure filters.

AngularJS Filters and Custom Filter

What is Filter in AngularJS?

A Filter in AngularJS helps to format the value of an expression for display to the user without changing the original value. For example, if you want a string shown in either lowercase or uppercase, you can do it using filters. Built-in filters such as ‘lowercase’ and ‘uppercase’ return the string in the requested case, and further filters exist for numbers, currency and JSON.

โš ๏ธ Version note: AngularJS (the 1.x branch) reached end of life on 31 December 2021 and receives no further security patches. Everything below remains accurate for maintaining existing AngularJS applications; in modern Angular the same role is filled by a pipe.

Filters are applied in the view with the pipe character. Before looking at each one, it helps to know why you would write your own.

Lowercase Filter in AngularJS

This filter takes a string and displays all of its characters in lowercase.

Below, a controller sends a string to the view via the scope object, and a filter converts it to lowercase.

Lowercase Filter in AngularJS

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Event Registration</title>
</head>
<body>
<h1> Guru99 Global Event</h1>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<div ng-app="DemoApp" ng-controller="DemoController">
Tutorial Name : <input type="text" ng-model="tutorialName"><br>
This tutorial is {{tutorialName | lowercase}}
</div>

<script>
var app = angular.module('DemoApp', []);

app.controller('DemoController', ['$scope', function($scope) {
  $scope.tutorialName = "Angular JS";
}]);
</script>
</body>
</html>

Code Explanation

  1. The mixed-case string “Angular JS” is placed in a member variable called tutorialName on the scope object.
  2. The filter symbol (|) marks the output for transformation, and the lowercase keyword applies the built-in filter that renders the whole string in lowercase.

โš ๏ธ Corrections applied to every listing. All six original examples shared three defects. chrset="UTF 8" is not a valid attribute or encoding, and is now charset="UTF-8". angular-route.js loaded before angular.min.js, which throws a module error, and was never used โ€” it has been removed, as has the unused jQuery reference. The text also claimed the value was “AngularJS” while the code set “Angular JS”; the text now matches.

Output:

Lowercase Filter in AngularJS

The mixed-case string is rendered entirely in lowercase. The opposite transformation works the same way.

Uppercase Filter in AngularJS

This filter is the counterpart of the lowercase filter, displaying every character in uppercase.

Below, a controller sends a string to the view via the scope object, and a filter converts it to uppercase.

Uppercase Filter in AngularJS

<!-- The head and library references are unchanged from the previous example -->
<div ng-app="DemoApp" ng-controller="DemoController">
Tutorial Name : <input type="text" ng-model="tutorialName"><br>
This tutorial is {{tutorialName | uppercase}}
</div>

<script>
app.controller('DemoController', ['$scope', function($scope) {
  $scope.tutorialName = "Angular JS";
}]);
</script>

Code Explanation

  1. The mixed-case string “Angular JS” is placed in tutorialName and attached to the scope object.
  2. The filter symbol (|) is followed by the uppercase keyword, so the built-in filter renders the whole string in uppercase.

โš ๏ธ Correction: the original introduced this section as “an example of capitalize filter AngularJS with the lowercase option”, which is wrong twice over. This section demonstrates the uppercase filter, and AngularJS has no capitalize filter at all โ€” capitalising only the first letter requires a custom filter, which the later sections show how to build.

Output:

Uppercase Filter in AngularJS

Case filters take no arguments. The next filter shows how a colon passes a parameter to a filter.

Number Filter in AngularJS

This filter formats a number and can limit how many decimal places are displayed.

The example below uses the number filter to display a value restricted to two decimal places. A controller sends the number to the view via the scope object, and the filter is applied in the view.

Number Filter in AngularJS

<!-- The head and library references are unchanged -->
<div ng-app="DemoApp" ng-controller="DemoController">
This tutorialID is {{tutorialID | number:2}}
</div>

<script>
app.controller('DemoController', ['$scope', function($scope) {
  $scope.tutorialID = 3.565656;
}]);
</script>

Code Explanation

  1. A number with many decimal places is placed in a member variable called tutorialID and attached to the scope object.
  2. The filter symbol (|) is followed by number:2. The colon passes an argument, and the 2 sets two decimal places. The value is rounded for display, so 3.565656 appears as 3.57 while the scope keeps the full number.

Output:

Number Filter in AngularJS

Formatting a plain number is often not enough when the value represents money, which is what the next filter handles.

Currency Filter in AngularJS

This filter formats a number as a currency value, prefixing it with a currency symbol such as $.

In the example below, a controller sends a number to the view via the scope object, and the currency filter is applied in the view.

Currency Filter in AngularJS

<!-- The head and library references are unchanged -->
<div ng-app="DemoApp" ng-controller="DemoController">
This tutorial Price is {{tutorialprice | currency}}
</div>

<script>
app.controller('DemoController', ['$scope', function($scope) {
  $scope.tutorialprice = 20.56;
}]);
</script>

Code Explanation

  1. A number is placed in a member variable called tutorialprice and attached to the scope object.
  2. The filter symbol (|) is followed by the currency filter.

โš ๏ธ Correction: the original claimed the currency “depends on the language settings applied to the machine”. It does not. AngularJS uses the locale bundled with the library, en-US by default, so the symbol is $ regardless of the operating system. Load the matching angular-locale_*.js file, or pass the symbol directly: {{tutorialprice | currency:"ยฃ"}}.

Output:

Currency Filter in AngularJS

Strings and numbers are simple values. The final built-in filter deals with whole objects.

JSON Filter in AngularJS

This filter converts an object into a formatted JSON string, which is useful for inspecting scope data during development.

In the example below, a controller sends an object to the view via the scope object, and the JSON filter is applied in the view.

JSON Filter in AngularJS

<!-- The head and library references are unchanged -->
<div ng-app="DemoApp" ng-controller="DemoController">
This tutorial is {{tutorial | json}}
</div>

<script>
app.controller('DemoController', ['$scope', function($scope) {
  $scope.tutorial = { TutorialID: 12, tutorialName: "Angular" };
}]);
</script>

Code Explanation

  1. An object holding TutorialID: 12 and tutorialName: "Angular" is placed in a member variable called tutorial and attached to the scope object.
  2. The filter symbol (|) is followed by the json filter, which serialises the object into indented JSON text.

โš ๏ธ Correction: the original described this value as “a number” and as “a JSON type string”. It is neither. It is a JavaScript object, and the json filter is what converts it into a JSON string for display.

Output:

JSON Filter in AngularJS

These five filters cover the common cases. When none produces the output you need, you write your own.

AngularJS Custom Filter

Sometimes the built-in filters in AngularJS cannot meet the requirements for formatting output. In such a case, an AngularJS custom filter can be created, which returns the output in the required manner.

A custom filter is registered on a module and then behaves exactly like a built-in one. The sections below cover the standard filters first, since a custom filter uses the same pipe syntax, then show how to build one.

How to Create Custom Filter in AngularJS

In the example below, a string passes from the controller to the view via the scope object, but should not be displayed as it is. A custom filter in AngularJS appends another string and displays the completed result.

Create Custom Filter in AngularJS

<!-- The head and library references are unchanged -->
<div ng-app="DemoApp" ng-controller="DemoController">
This tutorial is {{tutorial | Demofilter}}
</div>

<script>
var app = angular.module('DemoApp', []);

// The factory runs once; the function it returns runs on every value
app.filter('Demofilter', function() {
  return function(input) {
    return input + " Tutorial";
  };
});

app.controller('DemoController', ['$scope', function($scope) {
  $scope.tutorial = "Angular";
}]);
</script>

Code Explanation

  1. The string “Angular” is placed in a member variable called tutorial and attached to the scope object.
  2. AngularJS provides the filter registration method used to create a custom filter. ‘Demofilter’ is the name given to it, and that name is what the view refers to.
  3. This is the standard shape of a custom filter: the registered function is a factory returning the function that does the work. That function receives the value being filtered as its first parameter and returns the result โ€” here, the input with ” Tutorial” appended.
  4. The filter is applied in the view using the same pipe syntax as any built-in filter.

๐Ÿ’ก Tip: Filter names are conventionally lowercase or camelCase. ‘Demofilter’ works, but a name such as appendTutorial reads better and avoids clashing with a built-in name.

Output:

Create Custom Filter in AngularJS

The word ‘Tutorial’ has been appended to the string passed in the tutorial variable. This filter always appends the same text, which the next section makes configurable.

How to Pass Arguments to a Custom Filter

The filter above hard-codes the text it appends, so it can only do one thing. Built-in filters such as number:2 accept an argument after a colon, and a custom filter can too: every parameter after the first maps to a colon-separated argument in the view.

Three steps are involved: add parameters after input in the returned function, supply a default for anything optional so the filter still works when the argument is omitted, then pass the arguments in the view separated by colons.

app.filter('appendText', function() {
  return function(input, suffix, separator) {
    if (!input) { return input; }        // guard against undefined
    separator = typeof separator === 'undefined' ? ' ' : separator;
    return input + separator + suffix;
  };
});

The view then reads as follows, where “Tutorial” becomes suffix and the hyphen becomes separator.

{{tutorial | appendText:"Tutorial"}}          // Angular Tutorial
{{tutorial | appendText:"Tutorial":" - "}}    // Angular - Tutorial

Two details are easy to miss. Arguments are AngularJS expressions, so a literal string must be quoted, whereas an unquoted word is read as a scope property. Filters also chain, each receiving the output of the previous one: {{tutorial | appendText:"Tutorial" | uppercase}}.

โš ๏ธ Warning: Keep a filter pure โ€” same output for the same input, no outside changes. AngularJS caches a pure filter and re-runs it only when the input changes. A filter that reads the clock or mutates a service must be marked $stateful, which disables that caching and runs the filter on every digest cycle, a common cause of sluggish pages.

Filters are not restricted to templates. The same filter can be called from JavaScript, as shown next.

How to Use Filters in a Controller with the $filter Service

Applying a filter in the view is the common case, but the transformed value is sometimes needed inside the controller, for example before sending data to a server. AngularJS exposes every registered filter, built-in and custom alike, through the $filter service. Inject it, call it with the filter name to retrieve the filter function, then invoke that with the value and any arguments.

app.controller('DemoController', ['$scope', '$filter',
function($scope, $filter) {
  $scope.tutorial = "Angular";

  // Built-in filters, called from JavaScript
  $scope.shouted = $filter('uppercase')($scope.tutorial);      // "ANGULAR"
  $scope.price   = $filter('currency')(20.56);                 // "$20.56"

  // A custom filter works exactly the same way
  $scope.full    = $filter('appendText')($scope.tutorial, "Tutorial");
}]);

A shorter form also exists: injecting the filter name followed by Filter, such as uppercaseFilter, provides the filter function directly and it can be called immediately. Both forms resolve to the same function, so the choice is stylistic.

Two uses come up repeatedly. The first is preparing a payload: a date usually has to reach an API in a fixed pattern, and $filter('date')(value, 'yyyy-MM-dd') produces it without touching the value bound to the form. The second is narrowing a collection once in the controller, rather than leaving orderBy in an ng-repeat expression where it re-runs on every digest.

Filters injected this way are still registered on the module, so a custom filter must be declared with app.filter before any controller asks $filter for it. Otherwise AngularJS throws an unknown provider error.

Calling a filter in JavaScript differs from a template in one important way: the result is computed once and stored on the scope rather than recalculated on every digest. That makes it the faster option for a value that rarely changes, and the wrong option for one that must track user input.

FAQs

No. AngularJS ships lowercase and uppercase only. Capitalising the first letter of each word requires a custom filter that splits the string and rebuilds it, or a CSS text-transform rule if the change is purely visual.

The filter is registered on a different module from the one bootstrapped by ng-app, or the script defining it runs before AngularJS loads. Register the filter on the same module and load the library first.

Yes. Piping a collection inside ng-repeat filters or orders the items before they are rendered. The filter receives the whole array and must return an array.

Yes. AI assistants produce the factory, the returned function and the view syntax from a plain description of the formatting rule. Check that the generated filter guards against undefined input.

AI tools rewrite the factory as a class implementing PipeTransform and move each extra parameter into the transform method. Review any $stateful filter by hand, because impure pipes must be declared explicitly.

Summarize this post with: