Angularjs Filters

w‮.ww‬theitroad.com

In AngularJS, filters are used to format and manipulate data before it is displayed in the view. Filters can be used to modify text, format numbers and dates, sort and filter arrays, and more.

Filters in AngularJS are applied using the | symbol in the HTML. Here are a few examples:

<!-- Uppercase filter -->
<p>{{ 'hello world' | uppercase }}</p>
<!-- Output: HELLO WORLD -->

<!-- Number filter -->
<p>{{ 1234.5678 | number:2 }}</p>
<!-- Output: 1,234.57 -->

<!-- Date filter -->
<p>{{ '2022-03-01T12:34:56' | date:'dd/MM/yyyy' }}</p>
<!-- Output: 01/03/2022 -->

In the above examples, the uppercase, number, and date filters are used to modify the data before it is displayed in the view.

Custom filters can also be created in AngularJS by defining a new filter function. Here's an example:

angular.module('myApp', [])
.filter('reverse', function() {
  return function(input) {
    return input.split('').reverse().join('');
  };
});

In this example, we define a new filter called reverse that takes an input string, splits it into an array of characters, reverses the order of the characters, and then joins them back together into a string.

We can then use this filter in our HTML like this:

<p>{{ 'hello world' | reverse }}</p>
<!-- Output: dlrow olleh -->

Filters are a powerful tool in AngularJS that allow us to easily manipulate and format data in the view without cluttering up our controller logic.