Creating a ‘Starts With’ Filter in AngularJs

Hey everyone,

Just a quick post on how to create a simply custom filter in AngularJS. We’ll be using the same regions objects as the other day:

	"regions": [
			"id": "1",
			"postcode": "4700",
			"name": "Rockhampton",
			"description": "One of the major cities in Central Queensland."
			"id": "16",
			"postcode": "4214",
			"name": "Keppel Island",
			"description": "Awesome islands, very few people, heaps of fish beautiful clear water."

We’ll create the filter like so:

app.filter('regionsWithPostcode', function(){
	return function(regions, postcode){
		//Create vars
		var matching_regions = [];		
		//Check if input matches current postcode
		if(regions && postcode){		 	
		 	//Loop through each region
			for(var i = 0; i < regions.length; i++){
				if(regions[i].postcode.substr(0, postcode.length) == postcode){
			//Return matching regions
			return matching_regions;
			return regions;

And finally, we’ll setup the HTML as follows:

	<div class='postcode'>
		<input type='text' ng-model='search_postcode' placeholder='_ _ _ _'/>
		<button class='btn green' ng-class='{disabled: postcodeValid == false}'>Use Postcode</button>
	<div class='suburbs'>
		<div ng-repeat='region in regions | regionsWithPostcode:this.search_postcode' ng-animate='"region"' class='region' ng-click='setPostcode("1")'>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.