angular.filter

Work In Progress This page is currently being revised. It might be incomplete or contain inaccuracies.

Overview

Filters are a standard way to format your data for display to the user. For example, you might have the number 1234.5678 and would like to display it as US currency: $1,234.57. Filters allow you to do just that. In addition to transforming the data, filters also modify the DOM. This allows the filters to for example apply css styles to the filtered output if certain conditions were met.

Standard Filters

The Angular framework provides a standard set of filters for common operations, including: currency, json, number, and html. You can also add your own filters.

Syntax

Filters can be part of any angular.scope evaluation but are typically used with {{bindings}}. Filters typically transform the data to a new data type, formating the data in the process. Filters can be chained and take optional arguments. Here are few examples:

Writing your own Filters

Writing your own filter is very easy: just define a JavaScript function on angular.filter. The framework passes in the input value as the first argument to your function. Any filter arguments are passed in as additional function arguments.

You can use these variables in the function:

Example

The following example filter reverses a text string. In addition, it conditionally makes the text upper-case (to demonstrate optional arguments) and assigns color (to demonstrate DOM modification).

<script type="text/javascript"> angular.filter('reverse', function(input, uppercase, color) { var out = ""; for (var i = 0; i < input.length; i++) { out = input.charAt(i) + out; } if (uppercase) { out = out.toUpperCase(); } if (color) { this.$element.css('color', color); } return out; }); </script> <input name="text" type="text" value="hello" /><br> No filter: {{text}}<br> Reverse: {{text|reverse}}<br> Reverse + uppercase: {{text|reverse:true}}<br> Reverse + uppercase + blue: {{text|reverse:true:"blue"}}