动态orderBy在AngularJS中

Wou*_*ter 6 javascript sorting angularjs angularjs-ng-repeat

根据下拉菜单中的值,我有一个动态排序的对象数组.这是我目前在我的列表中所拥有的:

ng-repeat="item in filteredItems = (items | filter:searchInput | orderBy:canBeAnything)"
Run Code Online (Sandbox Code Playgroud)

但问题是排序可以是对象的属性或使用函数的计算值.它也应该能够以降序排列(可选).

我知道我可以在orderBy后面的canByAnything变量中使用一个字符串来传递对象的属性,如:

“-creationDate” // descending ordering on creation date
“customer.lastname” // ascending ordering on customers last name
Run Code Online (Sandbox Code Playgroud)

我也知道我可以通过以下函数来命令:

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
Run Code Online (Sandbox Code Playgroud)

但我不知道并想要实现的是:

  • 如何组合它以便我可以使用函数进行排序以及对象的属性/属性.我是根据用户选择的内容动态地表示其中一个.哪个可以是属性或计算值,可以是降序还是升序.
  • 如何以递减方式对计算值进行排序

csb*_*nes 11

更新orderBy:myCalculatedValueFunctionorderBy:dynamicOrderFunction:

$scope.dynamicOrderFunction = function() {
    if (orderByString) {
        return '-creationDate';
    }
    else {
        return myCalculatedValueFunction;
    }
}
Run Code Online (Sandbox Code Playgroud)

orderBy还有一个第三个属性,它接受一个布尔值,并在将时反转orderBy true.(orderBy:dynamicOrderFunction:reverseOrder哪里$scope.reverseOrder = true; // or false)


编辑

实际上你会遇到试图以字符串方式切换orderBy的问题.查看这个jsfiddle以获得有效的动态订单功能.