Damien
Damien

Reputation: 4121

Angular JS Filter On date

I was wondering if anyone could help me with filter on dates within ng-repeat I have a text field that I enter the search text into for filter the results in my table

take this cut down example`

 <tr id="credentialsData" ng-repeat="credential in credentials.data | filter:credentialsSearchText">
      <td>{{credential.createdDate | date:'medium'}}</td>
 </tr>`

credential.createdDate comes back in the rest call in the format 2015-03-24T21:19:49Z

When I attach the medium date filter - it displays as Mar 24, 2015 9:19:49 PM

However when i search on the String Mar or 9:, I get no results. Angularjs searches on the base object and ignores the filter. I have read other options online where the person recommends adding different date formats into the json object but unfortunately that is not an option for me

Any help on this would be appreciated

Cheers Damien

Upvotes: 0

Views: 724

Answers (1)

Smithecus Oxide
Smithecus Oxide

Reputation: 11

You can use a custom function for the filter.

https://docs.angularjs.org/api/ng/filter/filter

 <tr id="credentialsData" ng-repeat="credential in credentials.data | filter:credentialsSearchText:compareCredentialDate">
      <td>{{credential.createdDate | date:'medium'}}</td>
 </tr>

In your controller, put a

$scope.compareCredentialDate = function(credential, expected) {
  // you have to inject '$filter' to use this:
  var dateFilter = $filter('date');

  // this is the value that "credential.createdDate | date:'medium'"
  // evaluates to:
  var formattedDateString = dateFilter(credential.createdDate, 'medium');

  // hypothetical matching method - you can implement whatever you
  // want here:    
  var isMatch = formattedDateString.indexOf(expected) >= 0;

  return isMatch;
}

Upvotes: 1

Related Questions