Create angularJS filter!

Lately I have been playing with AngularJS and I am in love with it. Angular has these really cool components called filters which are described as:

[custom_blockquote style=” grey”] A filter formats the value of an expression for display to the user. They can be used in view templates, controllers or services and it is easy to define your own filter. [/custom_blockquote]

hodorLets Get Started

So game of thrones season 4 will be here in a couple of months so I thought we should build a Hodor filter to honor the great and noble Hodor. 

Our filter will take a string and translate it into Hodor.

Since this is just a demo, we are going to set up a super simple app that has a controller which looks like this:


	
		My Custom Filter
		
		
	
	

		

{{pageHeading | hodor}}

As you can see this is a pretty simple angular app with a single controller that sets our page heading data. We display our pageHeading property and add our hodor filter. We also attach our pageHeading model to the textarea so we can see the filter in action!

Now lets move on to the filter. We are going to want to use this in all our projects so we need create a new module just for our filter, and call the filter service.

angular.module('hodor-filter', []).filter('hodor', function(){

	return function(input){
		var hodor = [
			'H',
			'o',
			'd',
			'o',
			'r',
			' '
		];

		var stringPos = 0;
		var hodorString = "";
		for (var i = 0; i <input.length; i++) {
			var chr = hodor[i%6];
			hodorString = hodorString + chr;
		}

		return hodorString;

	};

});
  • Lets take a look at whats going on here:
  • – Declare our hodor-filter module and hodor filter
  • – Return a function that gets passed an input parameter
  • – Set up a Hodor array we will use this to replace characters in the input string
  • – Loop through all the characters and replace them with the correlating Hodor character
  • – Return the new hodorString

And thats it! Creating a filter is that easy! If you would like to download the project it is available on GitHub Hodor-Angular-Filter

Author: barrettbreshears

I don't take showers, only blood baths.