Off the Ridge code

Off the Ridge Code Newsletter

Search

How to Angular – Part 3 – Filters in AngularJS

Published April 20, 2015 in AngularJS - 0Comments

Filters in AngularJS

In part 3 of How to Angular, I’d like to present built-in Filters and how to create custom filters.

Code example in Plunker.

I will also make a switch from JSFiddler to Plunker for my code examples. I feel that Plunker is better suited for Angular and for examples that are larger in scope.

I also reorganized the code a bit:

1. The main app is being bootstrapped from app.js file

2. The controller is in its own file MyFirstController.js

– What are Filters in AngularJS?

Filters in AngularJS format the values for presentation to the user but they do not alter in any way the underlying data.

Built-in Filters in AngularJS

AngularJS comes with a lot of built-in filters  and the way to use them:

<strong>{{data | filter}}</strong>
for instance, if I were to uppercase or lowercase all letters in a string I might write:

{{data.firstName | lowercase}}

or, if I wanted to display just the month from a date object I might write:

{{data.startDate | date:'MM'}}

What about a filter that does not exist? This is what the custom filters are for.

– Creating Custom Filters

To create a custom filter you simply register the filter with the module:

app.filter('filterName', function(){

// your filter

});

for example, let’s write a trivial filter that removes all spaces from a string:

app.filter('removeAllSpaces', function () {
     return function(str) {
            return str.replace(/\s/g, '');
   };
});

For a full example see my code sample.

Happy coding!

-Sebastian