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

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

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!



Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
javascript ,angularjs ,html5

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}