Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Invoking Angular JS Filters from Controller

DZone's Guide to

Invoking Angular JS Filters from Controller

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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:

$filter(‘filterName’)(params);

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!



What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
javascript ,angularjs ,html5

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}