---
title: "What is a Filter and how to use it in AngularJS, Explain with an example."  
description: "Filters are particularly useful for formatting dates, numbers, strings, and other types of data."  
author: "Manish Sharma"  
published: 2024-05-14  
updated: 2024-05-14  
canonical: https://www.mindstick.com/articles/335818/what-is-a-filter-and-how-to-use-it-in-angularjs-explain-with-an-example  
category: "angular js"  
tags: ["angular js", "javascript framework", "front-end development"]  
reading_time: 6 minutes  

---

# What is a Filter and how to use it in AngularJS, Explain with an example.

#### AngularJS Filters

In AngularJS, filters are used to format data displayed to the user. They can be applied to expressions in templates, [controllers](https://www.mindstick.com/forum/155596/how-do-asynchronous-controllers-work-in-asp-dot-net), services, or [directives](https://www.mindstick.com/blog/44/directives-in-asp-dot-net) to transform the output before it is rendered. Filters are particularly useful for **formatting dates**, **numbers**, **strings**, and other types of data.

## Syntax –

{{ [expression](https://www.mindstick.com/articles/1861/sqlite-expressions) | filterName:parameter1:parameter2:... }}

## Where:

- **expression** is the value to be filtered.
- **filterName** is the name of the filter function.
- **parameter1**, **parameter2**, etc., are optional parameters that can be passed to the filter function.

## Here are some built-in filters,

- **currency** Format a number to a [currency format](https://www.mindstick.com/blog/328/currency-format-in-javascript).
- **date** Format a date to a specified format.
- **filter** Select a subset of items from an array.
- **json** Format an object to a JSON string.
- **limitTo** Limits an array/string, into a specified number of elements/characters.
- **lowercase** Format a string to lower case.
- **number** Format a number to a string.
- **orderBy** Orders an array by an expression.
- **uppercase** Format a string to upper case.

**currency filter** formats a number to a currency format. By default, the locale currency format is used.

```html
Syntax
{{ number | currency : symbol : fractionsize }}
```

## Example -

```html
<div data-ng-init="price = 500">
    <p>Price = {{ price | currency }}</p>
    <p>Price = {{ price | currency : "INR" }}</p>
    <p>Price = {{ price | currency : "INR " }}</p>
    <p>Price = {{ price | currency : "USD " }}</p>
</div>
```

**date filter** formats a date to a specified format. The date can be a date object, milliseconds, or a datetime string like "2016-01-05T09:05:05.035Z". By default, the format is "MMM d, y" (Jan 5, 2016).

```html
Syntax
{{ date | date : format : timezone }}
```

## Example -

```html
<div data-ng-init="price = 500; today = '2016-01-05T09:05:05.035Z'">
    <p>Date = {{ today | date }}</p>
    <p>Date = {{ today | date : yyyy }}</p>
    <p>Date = {{ today | date : "dd.MM.y" }}</p>
    <p>Date = {{ today | date : "fullDate" }}</p>
    <p>Date = {{ today | date : "'today is ' MMMM d, y" }}</p>
</div>
```

**filter filter** allows us to [filter an array](https://www.mindstick.com/interview/34416/how-to-filter-an-array-using-numpy), and [return an array](https://www.mindstick.com/forum/33605/return-an-array-for-section-titles-in-table-view) containing only the **matching items**. This filter can only be used for **arrays**.

```html
Syntax
{{ arrayexpression | filter : expression : comparator }}
```

## Example -

```html
<div data-ng-init="subjects=['hindi', 'english', 'math', 'science', 'social science']">
    <ul>
        <li data-ng-repeat="subject in subjects | filter:'sc'">{{subject}}</li>
    </ul>
</div>
```

**lowercase filter** converts a string to lowercase letters.

```html
Syntax
{{ string | lowercase }}
```

**uppercase filter** converts a string to uppercase letters.

```html
Syntax
{{ string | uppercase}}
```

## Example -

```html
<div data-ng-init="subjects=['hindi', 'english', 'math', 'science', 'social science']">
    <p>Filter text with {{"LowerCase" | lowercase}} and {{"UpperCase" | uppercase}}</p>
    <ul>
        <li data-ng-repeat="subject in subjects | filter:'sc'">
            <span>{{ subject | lowercase }}</span> ++ <span>{{ subject | uppercase }}</span>
        </li>
    </ul>
</div>
```

**number filter** formats a number to a string.

```html
Syntax
{{ string | number : fractionsize}}
```

## Example -

```html
<div data-ng-init="weight = 99">
    <h1>{{weight | number}}</h1>
    <h1>{{weight | number}} kg</h1>
    <h1>{{weight | number : 3}} kg</h1>
</div>
```

**orderBy filter** allows us to [sort an array](https://www.mindstick.com/forum/157933/write-a-program-to-sort-an-array-of-integers-using-the-bubble-sort-algorithm). By default, strings are sorted alphabetically, and numbers are sorted numerically.

```html
Syntax
{{ array | orderBy : expression : reverse }}
```

## Example -

```html
<div data-ng-init="numbers=[5, 3, 8, 1, 9, 2]">
    <ul>
        <li data-ng-repeat="number in numbers | orderBy: ''">
            {{ number }}
        </li>
    </ul>
</div>
```

**How to create a [custom filter](https://www.mindstick.com/interview/34020/how-do-filters-work-in-angularjs-and-can-you-create-a-custom-filter) in AngularJS,**

In AngularJS, filters are used to format data displayed to the user. You can create custom filters to tailor the [data presentation](https://answers.mindstick.com/qa/102924/how-to-use-charts-and-graphs-for-better-data-presentation) according to [your needs](https://www.mindstick.com/articles/12875/blunders-you-must-avoid-while-hiring-java-developers-to-get-the-best-fulfilling-your-needs). Here's an example of how you can create a custom filter in AngularJS:

## Example -

```html
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>

<body>
    <div data-ng-app="customFilterApp" class="container" ng-controller="MainController">
        <div class="" data-ng-init="numbers = [1, 2,3, 7, 8, 15, 42, 65, 25, 12, 36, 74, 85, 96, 49]; text='Odd'">
            <p><span class="fw-bold text-capitalize">{{text}}</span> list</p>
            <ul>
                <li class="" data-ng-repeat="item in numbers | numberType:text" >{{item}}</li>
            </ul>
        </div>
        <div>
            <h1>Filter Here</h1>
            <!-- Create a form for filter data -->
            <form class="row g-3">
                <div class="col-12">
                    <label class="form-label fw-bold">Text</label>
                    <!-- create input box for send and recive user input to controller  -->
                    <input type="text" data-ng-model="searchText" placeholder="Search..." class="form-control" autofocus="true" />
                    <!-- show no of count filterd count -->
                    <div id="emailHelp" class="form-text fw-bold">{{(items | customFilter:searchText).length}} data
                        found.</div>
                </div>
                <!-- check count is >0 then show if condisin is fail then this div is hide-->
                <div class="col-12" data-ng-show="(items | customFilter:searchText).length > 0">
                    <p class="fw-bold mt-3">Filtered data.</p>
                    <!-- iterate the items -->
                    <ul >
                        <li data-ng-repeat="item in items | customFilter:searchText" data-ng-bind="item" data-ng-class="(searchText ? 'text-warning fw-bold' : '')"></li>
                    </ul>
                </div>
            </form>
        </div>
    </div>

    <script>
        angular.module('customFilterApp', [])
            .controller('MainController', function ($scope) {
                $scope.items = ["Apple","Apricot","Avocado","Banana","Bilberry","Blackberry","Blackcurrant","Blueberry","Boysenberry","Currant","Cherry","Cherimoya","Cloudberry","Coconut","Cranberry","Custard apple","Damson","Date","Dragonfruit","Durian","Elderberry","Feijoa","Fig","Goji berry","Gooseberry","Grape","Raisin","Grapefruit","Guava"];
            })
            .filter('reverse', function() { /*This is reverse filter it take a string and return the reverse of string */
                return function(input) {
                    if (!input) return '';
                    return input.split('').reverse().join('');
                };
            })
            .filter('numberType', function() { /* this is numberType custom filter it take an array of interger and numbertype like ['even', 'odd', 'prime'], It return value according to your choice. */
                return function(array, text) {
                    var filteredArray = [];
                    if (!text || !['even', 'odd', 'prime'].map(function(item) { return item.toLowerCase(); }).includes(text.toLowerCase())) {
                        return array;
                    }
                    switch (text.toLowerCase()) {
                        case 'even':
                            filteredArray = array.filter(function(item) {
                                return item % 2 === 0;
                            });
                            break;
                        case 'odd':
                            filteredArray = array.filter(function(item) {
                                return item % 2 !== 0;
                            });
                            break;
                        case 'prime':
                            filteredArray = array.filter(function(item) {
                                if (item < 2) return false;
                                for (var i = 2; i <= Math.sqrt(item); i++) {
                                    if (item % i === 0) return false;
                                }
                                return true;
                            });
                            break;
                    }
                    return filteredArray;
                };
            })
            .filter('customFilter', function () {
                return function (array, text) {
                    if (!text)
                        return array;

                    var filtered = [];
                    angular.forEach(array, function (item) {
                        if (item.toLowerCase().indexOf(text.toLowerCase()) !== -1) {
                            filtered.push(item);
                        }
                    });
                    return filtered;
                };
            });
    </script>
</body>
</html>
```

Thank you,

I hope you are enjoying this article.

---

Original Source: https://www.mindstick.com/articles/335818/what-is-a-filter-and-how-to-use-it-in-angularjs-explain-with-an-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
