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 makes 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 data to show on the front end, and there are some dates that come 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 the JSON date to a string using a custom filter. Here, you will also learn how to write custom filters 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 the 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 characters. Now in order to show this Data in Small grid, table, etc. There creates an issue of padding etc. Now to resolve this issue in angular, it's very easy to limit the large string to some specific length.
And show all data in the tooltip.
If we did this in JQuery
  • We have to check the length of the character.
  • If greater than specific length then use the 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!