AngularJS orderBy不使用自定义函数

时间:2017-10-23 03:15:49

标签: javascript angularjs angularjs-orderby

目前,我创建了自定义函数来创建,以便从Moment中找到fromNow,我想根据函数返回的值对数据进行排序。

我想将表格元素放在顶部从现在开始的日期较小

在下表中从今天开始的31天在第二列是较小的,我想把这个元素放在顶部,我尝试过以下方式,但它没有工作

有人能帮助我吗?

Table Demo

AngularJS OrderBy

<tr ng-repeat="x in Holidays|orderBy:findFromNow">
                <td>{{$index+1}}</td>
                <td>{{x.Day}}</td>
                <td>
                <span class="label label-warning">{{findFromNow(x.Date)}} Days From Today</span></td>
                </tr>

功能

$scope.findFromNow = function (inputDate) {
        var m = moment(inputDate, "D-MMM-YY");
        var today = moment().startOf('day');
        var days = Math.round((today - m) / 86400000);
        if (days > 0) {
            return 999;
        } else {
            return (days * (-1));
        }

    }

假期JSON

  [
    {
      "Day": "Monday",
      "Date": "2-Jan-17"
    },
    {
      "Day": "Monday",
      "Date": "20-Feb-17"
    },
    {
      "Day": "Monday",
      "Date": "29-May-17"
    },
    {
      "Day": "Monday",
      "Date": "3-Jul-17"
    },
    {
      "Day": "Tuesday",
      "Date": "4-Jul-17"
    },
    {
      "Day": "Monday",
      "Date": "4-Sep-17"
    },
    {
      "Day": "Thursday",
      "Date": "23-Nov-17"
    },
    {
      "Day": "Friday",
      "Date": "24-Nov-17"
    },
    {
      "Day": "Monday",
      "Date": "25-Dec-17"
    }
  ]

1 个答案:

答案 0 :(得分:2)

你应该在使用前刻写单独的函数或检查inputDate的类型,因为在orderBy中,inputDate是Object not Date

 $scope.sortDate = function(inputDate){
    var m = moment(inputDate.Date, "D-MMM-YY");
    var today = moment().startOf('day');
    var days = Math.round((today - m) / 86400000);
    if (days > 0) {
        return 999;
    } else {
        return (days * (-1));
    }

}

这是plnkr:

  

http://plnkr.co/edit/afgsPDBF5RXG5WviYrdU?p=preview

希望有所帮助