How to use Angular Filter in Controller, Factory, Service – Part 15

In last two posts, we explored about the Filters and saw that how easily we can create custom filter and use as Angular predefined filters. We have used these filters in views for a single as well as an array of items. This is a normal scenario but there could be some cases where you need to use these filters in other components like Controllers, Factory, and Services etc. I have seen many questions around this on different online forums. So I thought to discuss it in detail.

If you are new to Angular Filter or even if you have some idea about, I will highly recommend you to go through my below two earlier Posts then continue. In this post, I will use the same examples that I used in my previous two posts as well.

Exploring Filters in {{AngularJS}} – Part 13

Exploring Filters in {{AngularJS}} Contd. : Custom Filters – Part 14

Note – This post is a part of series of posts on AngularJS and it is fifteenth one. Click here to view all the post. Apart from that you can also use the navigation links for next and previous post in each post at the bottom to check all.

There are two ways to achieve it, we’ll discuss it in details.

First Way –

We can use a filter in a Controller by injecting $filter. The syntax looks like

function myController($scope, $filter)
{
...
$filter('<fliterName>')(<comma separated filter arguments>);
...
};

The above syntax is self explanatory. Lets see some examples

myangularapp.controller("mycontroller", function ($scope, $filter) {
    $scope.filteredvalueUpperCase = $filter('uppercase')('brij');
    $scope.filteredvaluelowercase = $filter('lowercase')('Mishra');
    $scope.filteredvaluecurrency = $filter('currency')('1250');
});

// HTML

<div ng-app="myangularapp" ng-controller="mycontroller">
    <span>
        Name - {{filteredvalueUpperCase}} {{filteredvaluelowercase}} 
        Prize Money : {{ filteredvaluecurrency}}
    </span>
</div>

Above we can see that I have used three predefined filters (uppercase, lowercase, currency) and assigned the filtered values in new properties of $scope and later used it in view. Let’s see it running

NormalFiltersThe Filters worked as expected. Similarly we can use custom filters in Controller as well. Let’s see

myangularapp.filter('ConvertoPhone', function () {
    return function (item) {
        var temp = ("" + item).replace(/\D/g, '');
        var temparr = temp.match(/^(\d{3})(\d{3})(\d{4})$/);
        return (!temparr) ? null : "(" + temparr[1] + ") " + temparr[2] + "-" + temparr[3];
    };
});

myangularapp.controller("mycontroller", function ($scope, $filter) {
    // Custom Filter
    $scope.filteredphonenovalue = $filter('ConvertoPhone')('1234567891');
});

In above examples, We have seen the Filter applied on single item. Similarly we can use the filters that can be applied on an array as

myangularapp.filter('RemoveSpecialCharacters', function () {
    return function (items) {
        var filtered = [];
        for (var i = 0; i &lt; items.length; i++) {
            var item = items[i];
            filtered.push(item.replace(/[^\w\s]/gi, ''));
        }
        return filtered;
    };
});

myangularapp.controller("mycontroller", function ($scope, $filter) {
    var textValues = ['ab$h#cde&amp;fg@', 'ba$h#dcj&amp;fe@k#', 'ab$hm*hdp&amp;ef@', 'ab$h#cdj&amp;hg$ed@'];
    // Filter applied on array of items
    $scope.filteredtextValues = $filter('RemoveSpecialCharacters')(textValues);
});

In the above example, I have applied the custom filter on array of items in controller. In the same way, pre-defined filter can be used.

Using Filters in Factory, Service, Directives-

As controllers are specific to views on the other hand we write the service using Factory or Service that are available and used globally. There could be some situations where we need to apply a Filter in any of the above. Similar as controller, as we inject the $filter in controller function, we can pass the same Factory/Service as well. Let’s see quickly

In Factory

// Injecting Filter in Factor
myangularapp.factory("myCustomService", function ($filter) {
    return {
        filteredData: $filter('uppercase')('brij'),
        filteredDataAnotherWay: $filter('lowercase')('Mishra')
    };
});

In Service

// Injecting Filter in Service
myangularapp.service('myCustomServiceV2', function ($filter) {
    this.filteredData = $filter('uppercase')('brij');
});

So we can see here that using the filter in other components is also same as controller.

Now lets see another way of using the Filter in this components

Second Way –

In first way, we have invoked the Filter in the said components using $filter and provided the filter name as parameter. Which internally invoked the appropriate filter. As we know that in JavaScript, everything is function, so there must be some function getting executed with the provided parameter when we provide a Filter. Let’s explore that.

To explain it in better way, I will take an example where I created a custom filter name ConvertoPhone . While bootstrapping, it must be storing the filter definition somewhere and then later must be used from there to invoke when we use (using $filter in above examples). Right!!  Let’s see how it is stored

FilterAnotherWaySo here we see that a variable suffix with value ‘Filter’ . That is used while registering the Filter with name as

name + suffix => ‘ConvertoPhone’ + ‘Filter’ = ConvertoPhoneFilter

So here we can see the Filter is stored as ConvertoPhoneFilter. Now let’s see that How it is invoked

FiltersinAnotherWay-2In above code, it is creating the name of the filter (‘ConvertoPhone’ + ‘Filter’ = ConvertoPhoneFilter) and fetching the function to execute. It means we can inject ConvertoPhoneFilter directly. The same is true for predefined filters as well. Above code are part of Angular library. Let’s see the example

FilterAnotherwayExHere above we can see that instead of passing $filter in controller, we are passing all the Filters (predefined and custom) with the updated name that we discussed above. Here I passed three predefined and one custom filter and that we used as a normal JavaScript function.

Similarly we can pass the Filters in Factory, Service etc. Complete example in attached with this post.

Hope you have enjoyed the Post. Do share your feedback and if want to see anything specific.

Cheers,
Brij

[18th Aug 2015 : Updated this post for Angular version 1.4.*]

5 thoughts on “How to use Angular Filter in Controller, Factory, Service – Part 15

  1. Pingback: Exploring Filters in {{AngularJS}} Contd. : Custom Filters – Part 14 | Code Wala

  2. Pingback: Dependency Injection (DI) in {{AngularJS}} – Part 16 | Code Wala

Leave a comment