【问题标题】:Angular ng-repeat orderBy multiple fields as one fieldAngular ng-repeat orderBy 多个字段作为一个字段
【发布时间】:2016-09-13 20:05:36
【问题描述】:

我的问题和orderBy multiple fields in Angular不一样。

我的数组有一些对象

{
  estimatedStartDate : "..."
}

有些有:

{
  actualStartDate : "..."
}

那么有没有办法通过考虑这两个字段来订购。

orderBy:['estimatedStartDate','actualStartDate'] 

^ 这不起作用。

这是一个小提琴:http://jsfiddle.net/g201tudg/1/

所以假设这两个字段相同然后排序?

【问题讨论】:

    标签: javascript angularjs sorting angularjs-ng-repeat angularjs-orderby


    【解决方案1】:

    向你的控制器添加这样的函数:

    $scope.sortByEitherDate = function(row) {
        if (row.actualStartDate) {
            return row.actualStartDate;
        }
        return row.estimatedStartDate;
    }
    

    然后用 orderBy:sortByEitherDate 按它排序

    工作小提琴:http://jsfiddle.net/g201tudg/4/

    【讨论】:

    • 在第二次返回时,您缺少row.
    • orderBy:sortByEitherDate 而不是 orderBy:'sortByEitherDate'
    【解决方案2】:

    https://stackoverflow.com/a/25116296/2474688
    试试这个,看看它是否有效。只是通过这个线程看起来他们正在通过自定义过滤器根据索引进行排序。

    【讨论】:

      【解决方案3】:

      您可以使用自定义 OrderBy 排序:

      <tr ng-repeat="contact in contacts | orderBy:randomSort"> 
      
      $scope.randomSort = function(contact) {
        // your condition
      };
      

      【讨论】:

        【解决方案4】:

        您可以编写自己的自定义订单函数。它需要一个参数 - 您的卡 - 并返回其中任何一个字段。

        JS

            $scope.sort = function(card) {
                return card.actualStartDate !== undefined ? card.actualStartDate : card.estimatedStartDate;
            }
        

        HTML

        <div ng-repeat="card in myCards | orderBy:sort">...</div>
        

        【讨论】:

          【解决方案5】:

          根据我的经验,Angular ngRepeat 顺序不喜欢未定义的值,因此将缺少的成员添加为 null 可以解决您的问题。

          顺便说一句,您不需要提及“doc”。写会员就够了。

          另外,编写自定义排序方法会消耗大量客户端资源。

          这是正确工作的编辑小提琴:http://jsfiddle.net/g201tudg/2/

          【讨论】:

          • 感谢我删除了文档。 ,这是我的自定义代码的一部分。你的小提琴不起作用。我应该看到 1 2 3 4 5 因为 B = 1, E = 2 等等
          猜你喜欢
          • 2015-08-27
          • 2013-06-06
          • 2016-03-08
          • 1970-01-01
          • 1970-01-01
          • 2016-01-26
          • 2015-02-25
          • 2013-01-21
          • 1970-01-01
          相关资源
          最近更新 更多