AngularJS 中的动态 orderBy [英] Dynamic orderBy in AngularJS
问题描述
我有一个对象数组,我想根据下拉菜单中的值动态排序.这是我目前在我的清单中所拥有的:
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
还有第三个属性,它接受一个布尔值,当 true
时将反转 orderBy.(orderBy:dynamicOrderFunction:reverseOrder
where $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屋!