Filters In AngularJS

Today, I want to share my recent activities in AngularJS. As all aspects of AngularJS are nice, but the one who caught my attention is the Filters, its a very amazing thing to use, really it make your work much easier.

As there are many Filters available in AngularJS, I will discuss the few very important filters here.

Date Filter

Step 1:
In JavaScript, we have many types of date to show on front end, and there are some dates that comes in the form of JSON, now here i will first show normal date filter and then JSON date filter.

  1. var App = angular.module("FiltersApp", []);  
  2. App.controller("FilterController", function ($scope)  
  3. {  
  4.     $scope.toDay = new Date();  
  5.     // $scope.toDay shouldequals to" Wed Jan 20 2016 19:45:33 GMT+0500  
  6. });  
In front end:
  1. <label>{{toDay|date : 'MMMM dd, yyyy'}}</label>   
Now check, it will show you January 20, 2016, change 'MMMM','dd' and give your desired result.

Step 2: In this step, I want to show you JSON date to string using custom filter. Here, you will also learn how to write custom filter for your project, etc.
  1. Json Format: /Date(1297246301973)/  
  2. var App = angular.module("FiltersApp", []);  
  3. App.filter("DateFilter", function ()  
  4. {  
  5.     return function (date)  
  6.     {  
  7.         if (date != null)  
  8.         {  
  9.             return new Date(parseInt(date.substr(6)));  
  10.         }  
  11.         return "";  
  12.     };  
  13. });  
In front end:

DateFilter is your Filter Name.
  1. <label>{{ toDay | DateFilter | date:"MM/dd/yyyy"}}</label>   
  2. //Output:01/20/2016  
LimitTo Filter

Well, I am working on JQuery and there is data whose length is greater than 200 character. Now in order to show this Data in Small grid, table etc. There creates issue of padding etc. Now to resolve this issue in angular, its very easy to limit the large string to some specific length.

And show all data in tooltip.

If we did this in JQuery:

 

  • We have to check length of character.
  • If greater than specific length then use substring method, etc.

Now in AngularJS, simply use the following:

  1. <tr>   
  2.    <td title="{{NOTES}}">{{ NOTES | limitTo:70}}</td>   
  3. </tr>   
It means, if character length is greater than 70, then do not show this in <td>, else show all characters in title. Enjoy Angular!

 

Up Next
    Ebook Download
    View all
    Learn
    View all