AngularJS中的动态orderBy [英] Dynamic orderBy in AngularJS

查看:93
本文介绍了AngularJS中的动态orderBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要根据下拉菜单中的值动态排序的对象数组.到目前为止,这是我的清单:

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).

我知道我可以在orderBy后面使用字符串作为canByAnything变量,并传递对象的属性,例如:

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:

  • 如何将其组合在一起,以便我可以将函数与对象的属性/属性结合使用进行排序.我的意思是根据用户的选择动态地选择一个或另一个.可以是属性或计算值,可以是降序还是升序.
  • 如何按降序对计算值进行排序

推荐答案

orderBy:myCalculatedValueFunction更新为orderBy:dynamicOrderFunction:

错误

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

orderBy还有一个3rd属性,该属性接受布尔值,并且在true时将颠倒orderBy. (orderBy:dynamicOrderFunction:reverseOrder其中$scope.reverseOrder = true; // or false)

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)

修改

您实际上会遇到尝试以这种方式在字符串之间切换orderBy的问题.检出此jsfiddle 以获取有效的动态订单功能.

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;
}

这篇关于AngularJS中的动态orderBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆