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}}
Leave a Reply