crowhill crowhill - 3 months ago 28
AngularJS Question

Compare dates inside ng-repeat

In my controller I have:

vm.today = new Date();
vm.calendar = ...fairly complicated logic...


In my view I have:

<tr ng-repeat="week in vm.calendar">
<td ng-repeat="day in week track by $index">
<div>
calendar date: {{ day.date }}<br>
today: {{ vm.today }}
</div>
</td>
</tr>


Here's what's in a sample cell:

calendar date: 2016-09-01T00:00:00
today: "2016-09-07T16:58:12.434Z"


How could I add an
ng-if
to the above that would only show if
day.date
was greater than or equal to
vm.today


Something like this example (that doesn't work):

<tr ng-repeat="week in vm.calendar">
<td ng-repeat="day in week track by $index">
<div ng-if="day.date >= vm.today">
calendar date: {{ day.date }}<br>
today: {{ vm.today }}
</div>
</td>
</tr>


Thanks!

P.S. There is a similar question already on SO, but it didn't seem useful for my issue.

Answer

In cases like this you should create a controller function that accepts two parameters and returns a boolean. Also consider that you may be comparing dates to strings, so parsing is required before you can perform a meaningful comparison. So your div tag would look something like <div ng-if="vm.shouldDateBeShown(day.date, vm.today)"> and your function should use a library like moment (my personal preference) to do parsing and comparing:

vm.shouldDateBeShown = function(dt, today){
  var datea = moment(dt);
  var dateb = moment(today);
  return datea.diff(dateb, 'days') >= 0; 
}