AngularJS - Filters

In my previous article I had described the AngularJs Data Binding & Controllers. You can read it from the following link:

 
If you have been using Angular for a while now, you might have felt the need to do similar things several times and sometimes in several controllers. In my early days, I had nothing much to do about it. I used to declare similar functions under the scope of multiple controllers, that were meant to do the same task, thus repeating the code. It never felt right, though.

 

Then I was introduced to the filters. Why don't I just walk this talk? Let's take an instance where we need to reverse a variable string. What I would earlier do, is declare a function under the scope of the controller. Something like:
  1. function oneCtrl($scope) {  
  2.     $scoep.message = “Shashank”;  
  3.     $scope.reversed = function (message) {  
  4.     return message.split(“”).reverse().join(“”);  
  5.   };  
  6. }  

And use it in HTML like:

  1. <div ng-controller=”oneCtrl”>  
  2. <input type=”text” ng-model=”message”/>  
  3. <h1> {{ reversed(message) }}</h1>  
  4. </div>  

Find this example working at: jsfiddle

But then, what is the use of AngularJS that boasts a code re-usability feature if I need to write this reversed() method in every controller? Reasonable doubt!

AngularJS has filters in store for this. What it suggests is something like this:

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

And use it in your HTML like this:

  1. <div ng-controller=”oneCtrl”>  
  2. <input type=”text” ng-model=”message”/>  
  3. <h1> {{ rmessage | reverse }} </h1>  
  4. </div>  

Yes, this is the syntax for applying a filter. Using a pipe '|' followed by the name of the filter.

Find it working here: jsfiddle

AngularJS: ngFilter

Now that we have learned to create our custom filters, I should definitely not forget to mention about the predefined filters by Angular available for our use.

I'll use a big JSON object to present the data from, on which we'll apply the filters. This object will be returned by a service. For instance:

  1. myApp.factory(“Avengers”, function() {  
  2. var Avengers = {};  
  3. Avengers.cast = [  
  4. {  
  5.     name: 'Robert Downey Jr.',  
  6.     character: 'Tony Stark / Iron Man'  
  7. },  
  8. .  
  9. {  
  10.    name: 'Samuel L. Jackson',  
  11.    character: 'Nick Fury'  
  12. }  
  13. ];  
  14. return Avengers;  
  15. });  
  16.    function avenrgersCtrl($scope, Avengers) {  
  17.      $scope.avengers = Avengers;  
  18. }; 

So having defined the avengers model from the service into our scope, let's move on to the HTML part.

  1. <body ng-app=”myApp”>  
  2. <div ng-controller=”avengersCtrl”>  
  3.    <table>  
  4.      <tr ng-repeat=”actor in avengers.cast”>  
  5.        <td>{{ actor.name }}</td>  
  6.        <td>{{ actor.character }}</td>  
  7.     </tr>  
  8.   </table>  
  9. </div>  
  10. </body> 

You may notice the ng-repeat attribute here, that is a very powerful one, it helps us to loop through every item of a list, or an object. Before we start filtering, let's see this example working: jsfiddle

Let's set up a searchbox now to filter the results of this object into the table. Just make these additions to the code inside the "avangersCtrl":

  1. <div ng-controller=”avengersCtrl”>  
  2. <input type=”text” ng-model=”search” />  
  3. <table>  
  4.     <tr ng-repeat=”actor in avengers.cast | filter: search”>  
  5.        <td>{{ actor.name }}</td>  
  6.        <td>{{ actor.character }}</td>  
  7.     </tr>  
  8. </table>  
  9. </div>  

We are all set. This will definitely help you to filter results based on the keywords you type into the search box.

Additionally, to filter the results only by a specific key, like name or character only, just replace the model with:

  1. <input type=”text” ng-model=”search.name” />  

And now the results will only be based on the names present in the list that match the keyword you type in. See the working example here: jsfiddle

Other Built-in filters

Angular provides us with certain built-in filters that can be of great use and several of them can be stacked up on the same list.

For Instance:

  1. <tr ng-repeat=”actor in avengers.cast | orderBy: 'name'” />  

Will sort the result by name in ascending order. This order can be reversed by:

  1. <tr ng-repeat=”actor in avengers.cast | limitTo: 5” />  

Will return only the first five results from the list. To get the last five results, just do:

  1. <tr ng-repeat=”actor in avengers.cast | limitTo: -5” />  

Awesome right? Moreover,

  1. {{ actor.name | lowercase }}  

will convert all the characters of this string to the lowercase, for uppercase, use:

  1. {{ actor.name | uppercase }  
Previous Article: AngularJS - Data Binding & Controllers : Part 4

 

Up Next
    Ebook Download
    View all
    Learn
    View all