AngularJS Discovery Log - Custom Filters

One of the development skills I'm trying to build up is AngularJS and when I came across building custom filters, I was pretty surprised at how powerful and easy they were.  I like reusable code, who doesn't?  Custom filters help with that especially when you want to do something with the data such as reversing the text like in the example below.  Below is an example of how you can create your own filter and then use it in your view:


JavaScript

  1. myApp.filter('reverse', function() {
  2. return function(text) {
  3. return text.split('').reverse().join('');
  4. }
  5. });

 

Jade (View)

div {{data.message | reverse}}

So what's happening in the JavaScript code?

The filter function allows you to declare your own custom filter.  The first parameter is the name of the filter.  The second parameter is your callback function, where you would put in the code that will do something to the data that is passed in.

So what's happening in the Jade code?

A quick background information for you so you don't get confused if you don't know what Jade is.  Jade is a template engine for NodeJS and it is pretty fun using it.  Now, in the Jade code, in order to use the filter, you would type in a | (called a pipe), and then the name of the filter afterwards.  That's it! Easy right?


Final thoughts

I can definitely see the huge potential and impact this will have for me as a developer, so this has me pretty excited for learning AngularJS.

References: