Skip to content Skip to sidebar Skip to footer

Sorting Angularjs Ng-repeat By Date

I am relatively new to AngularJS. Could use some help I have a table with the following info

Solution 1:

Ideally you'd have a sortable object for date. One candidate is an isoformatted date:

i["date"] = i["date"].isoformat()

Now sorting should work just fine but it'll display wonky. So you'll need to use a date filter to format it on the UI:

<table>
 <tr>
  <th><span ng-click="sortType = 'first_name'; sortReverse = !sortReverse">Referral Name</span></th>
  <th><span ng-click="sortType = 'date'; sortReverse = !sortReverse">Referral Name</span></th>
 </tr>
 <tr ng-repeat="x in referral | orderBy:sortType:sortReverse">
  <td>name</td>
  <td>{{x.date | date : 'MMMM d, yyyy'}}</td>
 </tr>
</table>

Solution 2:

As you have noticed, the value you receive is type of string and therefore it is sorted alphabetically. You need to convert it into Date() beforehand. So basically what you need is to loop over the array of data you got and add a new property (or replace existing one) with a new Date object:

referral.forEach((ref) => {
    ref.date_obj = new Date(ref.date)
};

I just checked, JavaScript seems to be parsing format "September 13, 2016" pretty well.


Post a Comment for "Sorting Angularjs Ng-repeat By Date"