我正在尝试ng重复嵌套对象属性并对其进行排序,但排序对我不起作用。
我见过这个:如何使用嵌套属性在 AngularJS 中排序
但是 JSON 结构不同,我无法让它工作。
普伦克
我的代码:
<div ng-repeat="item in data | orderBy:order.allListPosition">
<div>{{item.name}} - {{item.order}}</div>
</div>
适用范围:
$scope.data = {
"78962": {
"id": "78962",
"name": "item 2",
"type": "blind",
"order": {
"allListPosition": "008",
"catListPosition": "059"
},
"data": {
"status": "stop",
"percent": 20
},
"longPress": {
"item": "78966",
"active": true
}
},
"78963": {
"id": "78963",
"name": "item 3",
"type": "coolmaster",
"order": {
"allListPosition": "053",
"catListPosition": "001"
},
"data": {
"status": 1,
"temp": 16,
"point": 25,
"mode": "cool",
"fan": 3
},
"longPress": {
"item": "78966",
"active": false
}
}
};
谁能告诉我我做错了什么?
非常感谢阿维
orderBy
在这里不起作用有两个原因:
-
orderBy
仅适用于数组,但您将其应用于普通对象。 - 要按表达式排序,您需要为
orderBy
提供表达式的字符串值。你给它order.allListPosition
,这相当于$scope.order.allListPosition
(不存在)。
要解决第一个问题,请添加数据对象的数组:
$scope.dataArray = Object.keys($scope.data)
.map(function(key) {
return $scope.data[key];
});
要解决第二个问题(并合并上面的dataArray
):
<div ng-repeat="item in dataArray | orderBy:'order.allListPosition'">
http://plnkr.co/edit/BXgYPTElSM3sjvLg30CL?p=preview
您可以创建自定义筛选器以按 neasted 属性排序。
myApp.filter('customorder', function() {
return function(items) {
items.sort(function(a,b){
// Make sure we are comparing integers
var aPos = parseInt(a.order.allListPosition);
var bPos = parseInt(b.order.allListPosition);
// Do our custom test
if (aPos > bPos ) return 1;
if (aPos < bPos) return -1;
return 0;
})
}
});
您的 html 将如下所示
<div ng-repeat="item in data | customorder">
<div>{{item.name}} - {{item.order}}</div>
</div>
你应该始终认为角度不是一种反击性语言。 您通常使用的过滤器内置在过滤器中。但是您可以在需要时尽快使用自己的过滤器玩得开心!
您的data
对象是对象的对象,而不是对象的数组。
因此,orderBy
不起作用,因为它仅与数组兼容。
我已经更新了您的data
对象以使其工作:
$scope.data = [
{
"id": "78961",
"name": "item 1",
"type": "blind",
"order":{allListPosition:"093",catListPosition: "009"},
"data": {
"status": "up",
"percent": 80
},
"longPress": {
"item": "78966",
"active": true
}
},
{
"id": "78962",
"name": "item 2",
"type": "blind",
"order":{allListPosition:"008",catListPosition: "059"},
"data": {
"status": "stop",
"percent": 20
},
"longPress": {
"item": "78966",
"active": true
}
},
{
"id": "78963",
"name": "item 3",
"type": "coolmaster",
"order":{allListPosition:"053",catListPosition: "001"},
"data": {
"status": 1,
"temp": 16,
"point": 25,
"mode": "cool",
"fan": 3
},
"longPress": {
"item": "78966",
"active": false
}
}];
在 HTML 中:
<div ng-repeat="item in data | orderBy:'order.allListPosition'">
<div>{{item.name}} - {{item.order}}</div>
</div>
普伦克
确定这应该是:
<div ng-repeat="item in dataArray | orderBy:'item.order.allListPosition'">