Apr 19 2015

AngularJS Filters in 15 minutes

Everything there is to know about Angular filters

How to use a filter in HTML:
Using the pipe | syntax you can apply any filter. Here we are using the 'orderBy' filter.

<li ng-repeat="item in items | orderBy">item</li>

How to use filters with parameter:
Inserting a : after the filter name means what comes after is the parameter. In this case the number by which you want to limit the list.

<li ng-repeat="item in items | limitTo:4">item</li>

How to use the 'limitTo' filter in JavaScript:
Inject the $filter into your Controller.

myController($scope, $filter)
Then call the filter service using the following syntax.
$filter('limitTo')(4);

How to use the multiple filters:
You can separate multiple filters using pipe | and they will apply in order of use.

<li ng-repeat="item in items | limitTo:4 | orderBy">item</li>

How to create a custom filter:

//Set up angular module
var app = angular.module('app', []);

//Create a new filter called 'myFilter'
app.filters('myFilter', function(){

	//This filter takes an input and adds $ in front of it
	return function(input){
		return "&" + input;
	};
});

How to create a custom filter with multiple parameters: First create a filter that accepts multiple parameters in its returning function.

//Create a new filter called 'myFilter'
app.filters('myFilter', function(){

	//This filter takes two parameters, input1 and input2
	return function(input1, input2){
		return input1 / input2;
	};
});
Call it from your Partial.
<div>100 | myFilter:50</div>
Or your Controller.
//Divide 100 by 50
$filter('myFilter')(100, 50);