In AngularJS, filters are functions that help format the data displayed to the user. They allow you to transform the data before rendering it in the UI without changing the original data source.
Common Uses of Filters:-
Formatting Data:
Filters are often used to format data in a user-friendly way. For instance:
-
currency:
Formats a number into a currency format. -
date:
Formats a date into a specified format. -
number:
Formats a number to a specified number of decimal places.
-
-
Filtering Lists:
Filters can be used to filter arrays or lists based on certain criteria.
-
filter:
Filters an array based on specified criteria. -
orderBy:
Orders an array by a specific property.
-
- Custom Filters: AngularJS allows you to create custom filters tailored to your specific requirements.
Usage in HTML Templates:
<!-- Example 1: Formatting -->
<p>{{ someNumber | currency }}</p>
<p>{{ someDate | date: 'MM/dd/yyyy' }}</p>
<!-- Example 2: Filtering Lists -->
<div ng-repeat="item in items | filter: { category: 'Books' }">
{{ item.name }}
</div>
<div ng-repeat="item in items | orderBy: 'price'">
{{ item.name }} - {{ item.price | currency }}
</div>
Custom Filters:
You can create custom filters by registering a new filter function with your AngularJS module. Here's an example:
angular.module('myApp', []).filter('myCustomFilter', function() {
return function(input) {
// Logic to transform input data
return transformedData;
};
});
Then, in your HTML template:
<p>{{ someData | myCustomFilter }}</p>
Benefits of Filters:
- Reusability: Filters allow you to apply the same data transformation logic across different parts of your application.
- Separation of Concerns: Filters help maintain a separation between the view and the business logic, making the code more maintainable.
- Cleaner Templates: Using filters in templates keeps them concise by avoiding complex logic.
AngularJS filters are powerful tools that enhance the presentation of data in the UI, allowing for easy formatting, sorting, and customization without altering the original data.