AngularJS Filters

In AngularJS, filters are powerful tools used to transform and format data directly within your templates (views). The core philosophy behind filters is the separation of concerns: your underlying data model should remain clean and "raw," while the filter handles how that data is visually presented to the user.

Developer Tip: Think of filters as "view-only" transformations. They don't change the actual value stored in your database or scope; they only change how it looks on the screen.

Key Features of Filters

  1. Formatting Data: Effortlessly convert raw numbers into currency, format dates into readable strings, or change text casing.
  2. Chainable: You can apply multiple filters to a single expression by using the pipe (`|`) symbol repeatedly. For example: {{ price | currency | uppercase }}.
  3. Reusable: Once a filter is defined, it can be used across your entire application—inside HTML templates, JavaScript controllers, or even other services.
  4. Customizable: While AngularJS comes with many built-in filters, you can easily write custom logic to handle unique business requirements.
Best Practice: Use filters for simple UI formatting. If you need to perform heavy data manipulation or complex logic, do it in the controller or service before the data reaches the view to keep your application snappy.

 

Common Built-in Filters

1. currency

This filter turns a number into a localized currency string. By default, it uses the '$' symbol, but you can specify any currency symbol or code.

{{ price | currency }} 
{{ price | currency:'€' }} 
Watch Out: The currency filter only formats the display. It does not perform real-time exchange rate conversions.

2. date

Dates in JavaScript are often messy. The date filter allows you to turn timestamps or Date objects into human-friendly formats.

{{ currentDate | date:'yyyy-MM-dd' }} 
{{ currentDate | date:'fullDate' }} 

3. filter

One of the most used filters, it selects a subset of items from an array based on a search string or object. It is most commonly used with ng-repeat to create live search features.

<input ng-model="searchText" placeholder="Search customers...">
<ul>
  <li ng-repeat="user in users | filter:searchText">{{ user.name }}</li>
</ul>
Common Mistake: By default, the `filter` provider does a case-insensitive substring match. If you need an exact match, you might need to pass an additional `true` argument or a custom comparator function.

4. json

This is a developer’s best friend. It converts a JavaScript object into a pretty-printed JSON string. It’s incredibly useful for debugging what’s actually inside your `$scope` variables.

<pre>{{ userData | json }}</pre>

5. limitTo

Limits an array or a string to a specific length. This is perfect for creating "Read More" snippets or pagination limits.

{{ blogPostContent | limitTo:100 }}... 

6. lowercase

Converts the entire string to lowercase. Useful for normalizing user input display.

{{ 'USER_NAME' | lowercase }} 

7. uppercase

Converts the entire string to uppercase. Great for headers or making specific UI elements stand out.

{{ 'warning' | uppercase }} 

8. number

Formats a number as a string. You can control the number of decimal places, which is helpful for scientific or financial data where precision matters.

{{ 1234.5678 | number:2 }} 

9. orderBy

Sorts an array based on an expression. You can sort by object keys, and even reverse the order by adding a minus sign.

<ul>
  
  <li ng-repeat="item in items | orderBy:'name'">{{ item.name }}</li>
  
  
  <li ng-repeat="item in items | orderBy:'-price'">{{ item.name }}</li>
</ul>

 

Using Filters in Controllers

While filters are most common in HTML, you sometimes need to format data inside your JavaScript logic. You can do this by injecting the $filter service into your controller.

Example:

app.controller('ProductController', function($scope, $filter) {
  var originalPrice = 123.45;
  
  // Access the 'currency' filter programmatically
  var currencyFilter = $filter('currency');
  
  // Apply it to a variable
  $scope.formattedPrice = currencyFilter(originalPrice, '€');
});
Developer Tip: You can also inject specific filters directly by appending "Filter" to the name, like `currencyFilter` or `dateFilter`, instead of injecting the entire `$filter` service.

 

Creating Custom Filters

If the built-in filters don't meet your needs, you can register your own. A filter is simply a factory function that returns a new function. The first argument is always the input data.

Example: Custom Filter to Reverse a String

app.filter('reverse', function() {
  return function(input) {
    // Ensure the input is a string to avoid errors
    if (!input || typeof input !== 'string') return '';
    
    return input.split('').reverse().join('');
  };
});

Usage in the View:

<p>Original: AngularJS</p>
<p>Reversed: {{ 'AngularJS' | reverse }}</p>
<!-- Output: SJralugnA -->
Watch Out: Filters run frequently during the AngularJS digest cycle. Avoid putting heavy computational logic (like complex regex or deep loops) inside a filter, as it can significantly slow down your UI.

 

Summary

AngularJS filters are an elegant way to manage data presentation without cluttering your controllers with formatting logic. By leveraging built-in filters like currency, date, and filter, you can create highly interactive and readable interfaces. For unique cases, the ability to create custom filters ensures your application remains flexible and maintainable as it grows.