Santosh
Santosh

Reputation: 885

Filter on date not working in angularjs

Given the data to filter:

$scope.friends = [
    { "name": 'John',    "phone": '555-1212',    "age": 10, "name-phone-age":now.setMinutes(now.getMinutes() + 30) },
    { "name": 'Mary',    "phone": '555-9876',    "age": 19, "name-phone-age":now.setMinutes(now.getMinutes() + 30) },
    { "name": 'Mike',    "phone": '555-4321',    "age": 21, "name-phone-age":now.setMinutes(now.getMinutes() + 30) },
    { "name": 'Adam',    "phone": '555-5678',    "age": 35, "name-phone-age":now.setMinutes(now.getMinutes() + 30) },
    { "name": 'Julie',   "phone": '555-8765',    "age": 29, "name-phone-age":now.setMinutes(now.getMinutes() + 30) }
  ];

Filter on any field using the search input box works except the DATE field;

For example

Search : John
Name    Phone Number    Age Some_Random_Date_Time

John    555-1212    10  2014-08-27 20:24:40 540

and Search for string 2014 which is part of output data as shown, returns with empty result

Name    Phone Number    Age Some Random Date Time
John    555-1212    10  2014-08-27 20:24:40 540
Mary    555-9876    19  2014-08-27 20:54:40 540
Mike    555-4321    21  2014-08-27 21:24:40 540
Adam    555-5678    35  2014-08-27 21:54:40 540
Julie   555-8765    29  2014-08-27 22:24:40 540


 Search : 2014
    Name    Phone Number    Age Some_Random_Date_Time

EXAMPLE LINK

Upvotes: 0

Views: 930

Answers (1)

PSL
PSL

Reputation: 123739

Search Filter on date actually works fine. Issue is with your data. Filter works on the data being bound to it. In your example only your display uses a date format filter to display the date in a specific format. If you use search filter it works on the list it is iterated upon (and remember date format filter does not update the underlying model), So either create a custom filter which can handle date in a formatter manner. But in your case since you need to have the formatted date displayed, i would just format the date in the model itself.

  //Add a new property or update the existing property, here i am adding a new one.
  //Or just use friends.forEach
  angular.forEach(friends, function(friend){
     friend.formattedDate = $filter('date')(friend['name-phone-age'],'yyyy-MM-dd HH:mm:ss');
  }) ;

   $scope.friends = friends;

And now remove the unwanted filter from the view, instead use this field.

 <td>{{friend.formattedDate}}</td>

Plnkr

Upvotes: 2

Related Questions