Using Native Filters in Angular, Not In The Markup

This post talks about a most common need while working with angularJS, the need to filter data using native filters provided by angular but not in the HTML template i.e. markup.

We might need such a scenario when we are computing/formatting the value to be filtered in some method & returning the value in the markup. It can be a date, a currency calculation (coming from server as x rupees & y paise, to be displayed as x+ y/100 rupees) or something which can be given to the native filter.

For eg: We want to format the time-stamp returned by a method in a date format we need.

We do the same in the markup/template as:

<div> {{myDateValue | date : 'dd/mm/yyyy'}}</div>

But consider a method returning you a time-stamp or a date string which has to converted into a valid date object & then has to formatted.

In such a case we would like to do the filtering in our controller.

For having a native filter to be available in our controller we need $filter service to be injected.

angular.directive('myCustomDirective', function($filter){
  return {
    compile: function(){
            return function(scope){
                  scope.getFormattedDate = function(date, format){
                       return $filter('date').(new Date(date), format);
                  };
           };
    };
  };
});

We can then use the scope method on our markup as:

<div> {{getFormattedDate(myDateValue, 'dd/mm/yyyy')}}</div>

This extends the use-case to the scenario where you have to add/modify the date value before formatting it.

scope.getFormattedDate = function(date, format){
 return $filter('date').(new Date(new Date(date).getDate() + 3), format);
};

Thumb Rule: “For any operation in the data to make it filter ready & if we have to get back to JS code, to apply native filter we need $filter service.”

Advertisements

One thought on “Using Native Filters in Angular, Not In The Markup

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s