Dynamic orderBy in AngularJS

我的梦境 提交于 2019-12-29 07:45:50

问题


I have an array of objects I want to order dynamically, based on a value from a drop down menu. This is what I have so far in my list:

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

But the problem however is that the sorting can be an attribute of the object or a calculated value using a function. It also should be able to sort in a descending way (optionally).

I know I can use a string for the canByAnything variable behind the orderBy passing an attribute of the object like:

“-creationDate” // descending ordering on creation date
“customer.lastname” // ascending ordering on customers last name

I also know I can orderBy a function like:

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

But what I don't know and want to achieve is:

  • How to combine it so I can use function(s) for sorting in combination with attributes/properties of the objects. I mean one or the other, dynamically, based on what the user has selected. Which can be an attribute or a calculated value, either descending or ascending.
  • How to sort a calculated value in a descending way

回答1:


Update orderBy:myCalculatedValueFunction to something like orderBy:dynamicOrderFunction:

ERRONEOUS

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

orderBy also has a 3rd property that accepts a boolean and will reverse orderBy when true. (orderBy:dynamicOrderFunction:reverseOrder where $scope.reverseOrder = true; // or false)


edit

You will actually run into issues trying to switch orderBy between a string a function this way. Checkout out this jsfiddle for a working dynamic order function.

$scope.dynamicOrder = function(user) {
    var order = 0;
    switch ($scope.order.field) {
        case 'gender':
            order = gender_order[user.gender];
            break;
        default:
            order = user[$scope.order.field];
    }
    return order;
}



回答2:


So you have to create your own filter and do what ever you want in it, there's tons of example on google. Just search :

angular custom filter

Theses last days, i experience somes issues with filters creation and i found that: https://github.com/a8m/angular-filter

I've added it immediately in my dependcies, i know i will use it really soon. May be it will help you too. Don't forget to valid my answer if it helps you to resolve your problem ;)



来源:https://stackoverflow.com/questions/29635796/dynamic-orderby-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!