2015-04-14 38 views
6

我有一個對象數組我想要動態地訂購,基於從下拉菜單中的值。這是我到目前爲止在我的名單:動態orderBy在AngularJS

ng-repeat="item in filteredItems = (items | filter:searchInput | orderBy:canBeAnything)" 

但是,不管問題是,排序可以是對象的屬性或使用功能的計算值。它也應該能夠以降序(可選)進行排序。

我知道可以使用一個字符串爲ORDERBY背後的canByAnything變量傳遞的對象的屬性,如:

「-creationDate」 // descending ordering on creation date 
「customer.lastname」 // ascending ordering on customers last name 

我還知道我可以ORDERBY的功能,如:

orderBy:myCalculatedValueFunction // will order in an ascending way based on a calculated value, for example calculating the total price of the object if it was an order or something 

但我不知道和想要達到的是:

  • 如何組合它,所以我可以使用函數(s)排序我n與對象的屬性/屬性組合。我的意思是動態的,基於用戶選擇的內容。可以是屬性或計算值,可以是降序或升序。
  • 如何降序方式

回答

10

更新orderBy:myCalculatedValueFunctionorderBy:dynamicOrderFunction排序的計算值的東西:

$scope.dynamicOrderFunction = function() { 
    if (orderByString) { 
     return '-creationDate'; 
    } 
    else { 
     return myCalculatedValueFunction; 
    } 
} 

orderBy也有接受boolean,將反向排序依據時true第3財產。 (orderBy:dynamicOrderFunction:reverseOrder其中$scope.reverseOrder = true; // or false


編輯

你實際上會碰到試圖這樣一個字符串之間切換排序依據的功能的問題。檢出this jsfiddle以獲得有效的動態順序功能。

+0

此作品非常有用 –

0

所以你必須創建你自己的過濾器,並做任何你想要的東西, 谷歌上有很多例子。只要搜索:

角度自定義過濾器

論文最後的日子裏,我遇到薩姆問題有過濾器的創建,我發現: https://github.com/a8m/angular-filter

我已經添加它立即在我dependcies,我知道我會盡快使用它。也許它會幫助你。 如果能幫助您解決問題,請不要忘記驗證我的答案;)