</>
Skip to content
AngularJS lessons (18/28)

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

  1. Create a truncate filter
  2. Add parameters
  3. Use filters in controllers
  4. 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.