Thursday, September 12, 2013

Custom Angular Filters

The current filter docs are a bit confusing. Let's break down how simple it is to add an Angular filter!

The currency filter does not allow you to choose how many decimals are involved. So let's create a custom filter that does currency in whole dollars.

var app = angular.module('app', ['dollarFilter']);
angular.module('dollarFilter', []).filter('dollars', function() {
 return function(value) {return "$" + addCommas(Math.round(value));}

You can now call this filter like so:

{{total | dollars}}

So, let's breakdown the code so we know exactly what we need to do.

We are creating an angular module.

angular.module('dollarFilter', []

We name the module 'dollarFilter'. The array brackets would be where you would list any dependent modules. So let's look at the controller init:

var app = angular.module('app', ['dollarFilter']);

dollarFilter is now a required module for our controller and will be loaded on start up.

Note that dollarFilter is the name of the module itself, NOT the name of our filter! This name is only used for the injector. Modules can contain multiple filters, coding, etc...

.filter('dollars', function() {

Here is where we actually name our filter. In this case, "dollars". That is the name we use when we want to call the filter.

Now we write the function. In the case of a filter, it will take one argument representing the value passed to our filter.

return function(value) {return "$" + addCommas(Math.round(value));}

I've set up a basic Fiddle for you to play with and see how the code works. (You can also get the "addCommas" function from here.)

What if we want to add multiple filters to one module?

Declare our filter, and store the object in a variable.
var df = angular.module('dollarFilter', []);

Add filters to the object:
df.filter('dollars', function() {
    return function(value) {return "$" + addCommas(Math.round(value));}
df.filter('percentage', function () {
    return function(value) {return value * 100 + "%";}

And here's another fiddle for you to see how it comes together.

Hope this helps. If there's a question we didn't answer, let me know in the comments.

No comments:

Post a Comment