Here are some basics on how to create your own Angular custom filters. Below I have created a controller with an array of numbers starting from 1 to 10 and I am going to write a custom filter for filtering even numbers and one for odd numbers.

app.controller('AppController', ['$scope', function($scope) {
		$scope.numbers = [1,2,3,4,5,6,7,8,9,10];
	}
]);

To filter even numbers only I created a filter called EvenNumbersOnly which is a function that takes an array of numbers and check each value to see they are even numbers:

app.filter('EvenNumbersOnly', [function() {
		return function(numbers) {
			var evenNumbers = [];
			for (idx in numbers)
			{
				if ((numbers[idx] % 2) == 0)
				{
					evenNumbers.push(numbers[idx]);
				}
			}
			return evenNumbers;
		}
	}
]);

For filtering odd numbers I have done the same thing except it only check for odd numbers 🙂

app.filter('OddNumbersOnly', [function(){
		return function(numbers) {
			var oddNumbers = [];
			for (idx in numbers)
			{
				if ((numbers[idx] % 2) == 1)
				{
					oddNumbers.push(numbers[idx]);
				}
			}
			return oddNumbers;
		}
	}
]);

So now we have our filters ready to be used I will create a html page that will display the original complete set of numbers in the first div element, then I display a set of even numbers using the EvenNumbersOnly filter in the second div element, and then I display a set of odd numbers using the OddNumbersOnly filter in the third div element. Please note that the filter must be used with a pipe after the value you want to filter with:

<html ng-app="app.demo">
	<head>
	<title>Learn AngularJS - Filters</title>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
	<script src="app.js"></script>
	</head>
	<body ng-controller="AppController">
		<div>
		Numbers: {{ numbers }}
		</div>
		<div>
		Even Numbers: {{ numbers | EvenNumbersOnly }}
		</div>
		<div>
		Odd Nimbers: {{ numbers | OddNumbersOnly }}
		</div>
	</body>
</html>

Download Source Code

Shares