Open In App

How to use filter within controllers in AngularJS ?

Last Updated : 05 Sep, 2022
Comments
Improve
Suggest changes
8 Likes
Like
Report

In this article, we will see how to use the Filter inside the controller using AngularJS. Filters are used to format the value of an expression and display it to the user. It can be used in HTML Previews, Controllers or Services, and directives. AngularJS facilitates many built-in filters, although, we can create & define the custom filters easily. The list of built-in filters in AngularJS is given below:

Built-in filters:

If a filter currency is injected by using the dependency currencyFilter. The injected argument is a function that takes the value to format as the first argument and filters parameters starting with the second argument. The following ways are used to implement the filter. 

Approach 1: Using filters in view templates 

Syntax:

  • By applying the Filters to expressions in view templates:
{{ expression | filter }} 
  • Filters can be applied to the result of another filter. It is called "chaining":
{{ expression | filter1 | filter2 | ... }}
  • Filters may have arguments:
{{ expression | filter:argument1:argument2:... }}

Example 1: This example describes the use of the Filter inside the controller in AngularJS.

Output: 

 

Approach 2: The filter is used in directives, services, and controllers. To achieve this, inject a dependency with the name of the filter into your directive/controller/service

Example 2: This is another example that describes the use of the Filter inside the controller in AngularJS.

Output: 

 

Approach 3: It is the modification of the second approach. Filters can also be added to AngularJS to format data values. There is $filter service that is used in our AngularJS controller. In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for the filter. 

Syntax:

$filter("filter")(array, expression, compare, propertyKey)
function myCtrl($scope, $filter) {
    $scope.finalResult = $filter("filter")(
        $scope.objArray, $scope.searchObj);
};

AngularJS has some built-in filters that can be used to reduce an array's execution or array at some points based on some condition.

$scope.formatDate = $filter("date")($scope.date, "yyyy-MM-dd");
$scope.finalResult = $filter('uppercase')($scope.name);

Example 3: In this example, the Filters are added to directives, like ng-repeat, by using the pipe symbol or character `|`, followed by a filter tag. 

Output:

 

Next Article

Similar Reads