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){
					matching_regions.push(regions[i]);
				}
			}

			//Return matching regions
			return matching_regions;
		}
		else{
			return regions;
		}		
	}
});

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

	
Use Postcode
{{region.name}}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s