AngularJS Filters
Key Concepts
Filters in AngularJS are used to format the data displayed to the user. They can be used in templates, controllers, or services to transform data without changing the original data source. Filters are particularly useful for tasks like formatting dates, currencies, and sorting arrays.
1. Currency Filter
The currency filter formats a number as a currency. By default, it uses the local currency symbol, but you can specify a different currency symbol if needed. This filter is useful for displaying monetary values in a consistent and readable format.
Example:
<p>Price: {{ 1234.56 | currency }}</p> <p>Price in Euros: {{ 1234.56 | currency:"€" }}</p>
In this example, the first line will display "Price: $1,234.56" (assuming the local currency is USD), and the second line will display "Price in Euros: €1,234.56".
2. Date Filter
The date filter formats a date to a specified format. You can use various placeholders to customize the date format, such as "yyyy" for the full year, "MM" for the month, and "dd" for the day. This filter is essential for displaying dates in a user-friendly way.
Example:
<p>Today's Date: {{ new Date() | date:"yyyy-MM-dd" }}</p> <p>Formatted Date: {{ new Date() | date:"MM/dd/yyyy" }}</p>
In this example, the first line will display today's date in the format "2023-10-05", and the second line will display it in the format "10/05/2023".
3. Filter Filter
The filter filter is used to filter an array based on a specified criteria. You can filter by a single property or use a more complex expression. This filter is handy for dynamically filtering lists of items in your application.
Example:
<input type="text" ng-model="searchText" placeholder="Search..."> <ul> <li ng-repeat="item in items | filter:searchText">{{ item.name }}</li> </ul>
In this example, as the user types in the input field, the list of items will be filtered based on the search text. Only items whose names match the search text will be displayed.
4. OrderBy Filter
The orderBy filter sorts an array by a specified expression. You can sort by a single property or use a more complex expression. This filter is useful for sorting lists of items in your application.
Example:
<ul> <li ng-repeat="item in items | orderBy:'name'">{{ item.name }}</li> </ul>
In this example, the list of items will be sorted alphabetically by their names. The orderBy filter ensures that the items are displayed in the correct order.