Filtering AngularJS items based on start and end date

There are cases where you would like to filter existing items in an AngularJS ng-repeat and only display the items where the date of the item is between any given start and end date. The following code accomplish that – please notice that I have only tested this with AngularJS version 1.2.22 and also notice that I use moment.js for the parsing of the date.

The following code is the filter – put this into a controller:

    // Daterange filter
    $scope.dateRangeFilter = function (property, startDate, endDate) {
        return function (item) {
            if (item[property] === null) return false;

            var itemDate = moment(item[property]);
            var s = moment(startDate, "DD-MM-YYYY");
            var e = moment(endDate, "DD-MM-YYYY");

            if (itemDate >= s && itemDate <= e) return true;
            return false;
        }
    }

And then – in your ng-repeat – you insert the following code:

    <tr ng-repeat="t in Result | filter: dateRangeFilter('itemDate', startDate, endDate)">
        <td>{{t.Name}}</td>
        <td>{{t.Adresse}}</td>
        <td>{{t.Phone}}</td>
        <td><a ng-href="mailto:{{t.Email1}}">{{t.Email1}}</a></td>
        <td>{{t.itemDate | dateFilter | date:"dd-MM-yyyy"}}</td>
    </tr>
Advertisements

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