Creating an AngularJS Filter

If we were to build an event system in an AngularJS site and wanted to show future events in an ng-repeat we could build a simple AngularJS Filter. Below is a filter that will only return items that have a date in the future.

angular.module('app')
  .filter('isFuture', function() { // initialize the filter

    return function(items, date) { // pass in the items (required) and any optional arguments

      return items.filter(function(item) { // filter the array

        return new Date(item[date]) >= new Date() // only return items that are in the future
      })
    }
  })

You can use the new filter in a template like below, where enddate is the variable you want to compare while applying the filter. This variable is passed into the filter function above using the optional argument named date.

<div ng-repeat="webinar in webinars | isFuture:'enddate'"> 
  <h4>{{webinar.title}}</h4> 
</div>

AngularJS Filters are very powerful factory functions that can be used throughout your application. Filters aren't just for ng-repeat but can be used anywhere you want to apply a special format. You can use filters to format the value of an expression in templates, controllers and/or services.

Need a filter to show events that happened in the past?

angular.module('app')
  .filter('isPast', function() { // initialize the filter

    return function(items, date) { // pass in the items (required) and any optional arguments

      return items.filter(function(item) { // filter the array

        return new Date(item[date]) < new Date() // only return items that are in the past
      })
    }
  })

Add new comment