Over a million developers have joined DZone.

Invoking Angular JS Filters from Controller

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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

There are two ways to invoke filters from controllers in AngularJS. 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 the name of a filter and returns the filter function. Once the function is obtained, we can pass in the required parameters. Here is the syntax:


Let’s invoke one of the most used filters, orderBy, using $filter to sort a list of items based on 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")

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 the name of the filter that is 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 the combined result.

$scope.items = filterFilter(orderBy(itemsArray, "Name"), "a");

The 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!

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Rabi (ravi) Kiran, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}