Wednesday, 4 December 2013

Invoking Angular JS Filters from Controller

In my post on Filtering and Sorting data using Angular JS, I got a comment requesting for a post on calling filters in a controller. We will see how to achieve the same in this post.

There are two ways to invoke filters from controllers in Angular JS. One approach is using the $filter service and the other is directly injecting the filters into the controller. Let’s see each of these cases.

Using $filter service
The $filter service is a provider that accepts name of a filter and returns the filter function. Once the function is obtained, we can pass in the required parameters. Following is the syntax:


Let’s invoke one of the most used filters, orderBy using $filter to sort a list of items based name. After getting the filter function, we need to pass the source array and sort expression to the filter function. Following statement shows this:

$scope.items = $filter('orderBy')(itemsArray, "Name")

To apply multiple filters, we can pass result of a filter as parameter to another filter. Following snippet applies a filter condition on the sorted list obtained above:
$scope.items = $filter('filter')($filter('orderBy')(itemsArray, "Name"), "a")

The filter condition and sort expression passed into the above filters can be any dynamic values as well. A custom filter can also be called using the same syntax. Say, rupee is a filter I wrote to display my currency in rupee format; we can invoke the filter as:
$scope.totalPrice= $filter('rupee')(totalPrice);

Getting filters injected into the controller
Filters can be injected into the controller, but name of the filter to be specified in the controller argument should be appended with the word “Filter”.

app.controller('MyCtrl', function(orderByFilter){  //injects the orderBy filter into the controller

As we have a reference to the filter available in the controller, we can invoke the filter directly from here.
$scope.items= orderByFilter(itemsArray, "Name");

The result obtained can be passed into another filter to get combined result.
$scope.items = filterFilter(orderBy(itemsArray, "Name"), "a");

Same syntax can be used to inject and use a custom filter as well. I have put together a sample on jsfiddle covering the above concept: Happy coding!

No comments:

Post a Comment

Post a Comment