比较ng-repeat内的日期

时间:2016-09-07 17:14:30

标签: angularjs

在我的控制器中我有:

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

在我看来,我有:

<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>

以下是样本单元格中的内容:

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

我如何在上面添加ng-if,只显示day.date是否大于或等于vm.today

像这个例子(不起作用):

<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>

谢谢!

P.S。 SO上已经有similar question,但它对我的问题似乎没什么用。

3 个答案:

答案 0 :(得分:1)

在这种情况下,您应该创建一个接受两个参数并返回布尔值的控制器函数。还要考虑您可能要将日期与字符串进行比较,因此在执行有意义的比较之前需要进行解析。所以你的div标签看起来像<div ng-if="vm.shouldDateBeShown(day.date, vm.today)">,你的函数应该使用像moment这样的库(我个人喜好)进行解析和比较:

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

答案 1 :(得分:0)

您可以创建过滤器。

 <td ng-repeat="day in week track by $index | dateCompare">

JS:

  .filter('dateCompare',function(){
            var arrFinalWeek = [];
            return function(weekInChild,weekDataFromParent){

                    var timeStamp = new Date(date).getTime();
                    weekInChild.forEach(function(date,key){

                            if(new Date(date).getTime() >= timeStamp){
                                arrFinalWeek = arrFinalWeek.concat(date);
//depend on requirement u can delete it from existing  or 
//concat new array and return it
                            }
                    });

                return arrFinalWeek;
            }
        })

答案 2 :(得分:0)

将ng-if条件修改为ng-if="day.date >= vm.today.toJSON()"

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

Fiddle example