2017-09-05 194 views
0

我已經有了對象的數組的數組具有以下結構上訂購的數組:Angularjs:如何基於對象的日期字段的子陣列

parentArr = [ 
[{id:1, date:1505020200000}, {id:4, date:1505020200000 }], 
[{id:2, date:1504681500000}], 
[{id:3, date:1504671000000}, {id:20, date:1504671000000}] 
] 

每個孩子數組將只包含日期是是相同的。

我試圖做的是使用角度的排序依據過濾器訂購從最舊到最新的日期,但我不確定如何做到這一點。

我已經試過排序依據過濾器設置爲一個變量,像這樣:

$scope.dateFilter= arr[0][0].date 
<div ng-repeat="child in parentArr | orderBy: dateFilter"> 

,但我敢肯定,我做錯了什麼。

編輯:

感謝一大堆馬修對他所有的工作幫助我,而且由於他的幫助下,我意識到我需要做的。使用array.sort是我最終需要的數據結構。

$scope.results.sort(function (a, b) { 
    return a[0].date - b[0].date; 
}); 
+0

嘗試'排序依據:「date'' – Ronnie

+0

@AaronCase有沒有在提交自己的答案,並標記爲_the_的答案,如果你發現了一個更直接的方法沒有壞處。幹得好,其餘的好運。 –

回答

0

添加getter函數以獲取要排序的值。

$scope.myDateGetter = function(item) { 
    return item[0].date; 
} 

然後將它作爲表達式參數傳遞給orderBy過濾器。

<div ng-repeat="child in parentArr | orderBy: myDateGetter"> 

如這裏記載:https://docs.angularjs.org/api/ng/filter/orderBy

1

創建自定義過濾器,以扁平化陣列:

(function(app){ 
    app.filter("flatten", function() { 
     return function(input) { 
      var output = []; 
      input.forEach(function(innerArr) { 
       output = output.concat(
        innerArr.map(function(obj) { return obj; }) 
       ); 
       return output; 
      }); 
      return output; 
     }; 
    }); 
}(angular.module("yourModule"))); 

那麼你ng-repeat變爲:

<div ng-repeat="child in parentArr | flatten | orderBy: 'date'"> 

CodePen Demo

+0

感謝馬修的偉大榜樣。我看到你的過濾器在做什麼,並且我意識到我並沒有正確地問我的問題。 –

+1

這裏是我如何得到我需要的東西: $ scope.results.sort(功能(A,B){ \t回報[0] .date - B [0] .date; }); –