AngularJS — Custom Filters
Basic Custom Filter
app.filter('truncate', function() {
return function(input, length) {
if (!input) return '';
if (input.length <= length) return input;
return input.substring(0, length) + '...';
};
});
<p>{{longText | truncate:50}}</p>
Filter with Parameters
app.filter('formatDate', function() {
return function(input, format) {
if (!input) return '';
var date = new Date(input);
if (format === 'short') {
return date.toLocaleDateString();
}
return date.toISOString().split('T')[0];
};
});
<p>{{myDate | formatDate:'short'}}</p>
Filter in Controller
app.controller('MyController', function($scope, $filter) {
$scope.items = [
{ name: 'Apple', price: 1.5 },
{ name: 'Banana', price: 0.75 }
];
$scope.filteredItems = $filter('filter')($scope.items, { name: 'Apple' });
});
Filter Chain
<p>{{name | uppercase | truncate:10}}</p>
<p>{{price | currency:'€' | number:2}}</p>
State Filter
app.filter('stateFilter', function() {
return function(input, state) {
if (!state) return input;
return input.filter(function(item) {
return item.state === state;
});
};
});
Mini Practice
- Create a truncate filter
- Add parameters
- Use filters in controllers
- Chain multiple filters
Up Next
Continue with HTTP — making HTTP requests.
Related Topics
Frequently Asked Questions about Custom Filters
What is Custom Filters in AngularJS?
Custom Filters is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Custom Filters?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Custom Filters.
Why is Custom Filters important in AngularJS?
Custom Filters is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.