假设我有两个ng-repeats,如
<div ng-repeat="category in categories">
{{category.name}}
<div ng-repeat="subcategory in category.subcategories">
{{subcategory.value}}
</div>
</div>
我想根据子类别订购类别。值?
JS:
$scope.categories = [
{
name: "1st category",
subcategories: [
{
name: "1st subcategory",
value: 1
},
{
name: "2nd subcategory",
value: 2
}
]
},
{
name: "2nd category",
subcategories: [
{
name: "3rd subcategory",
value: 5
},
{
name: "4th subcategory",
value: 6
}
]
},
{
name: "3rd category",
subcategories: [
{
name: "4th subcategory",
value: 3
},
{
name: "5th subcategory",
value: 4
}
]
}
];
还制作了一个Plunker: https://plnkr.co/edit/8ugJckYRrZoyQlnBYkuU
预期结果应为:
2nd category
6
5
3rd category
4
3
1st category
2
1
答案 0 :(得分:1)
通过创建customOrderBy来解决它。
HTML:
<div ng-repeat="category in categories | customOrderBy:'subcategories':'value':true">
JS:
.filter('customOrderBy', function() {
return function(items, field, value, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
item.subcategories.sort(function(a, b){
return a[value]-b[value];
});
if(reverse) item.subcategories.reverse();
filtered.push(item);
});
filtered.sort(function (a, b) {
return (a[field][0][value] > b[field][0][value] ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
这里是Plunker:https://plnkr.co/edit/8ugJckYRrZoyQlnBYkuU?p=preview
答案 1 :(得分:0)
在此代码下方:
<div ng-repeat="category in categories | orderBy:'name':true">
{{category.name}}
<div ng-repeat="subcategory in category.subcategories | orderBy: 'value':true">
{{subcategory.value}}
</div>
</div>
答案 2 :(得分:0)
对于您的预期结果:
<div ng-repeat="category in categories | orderBy: '-name'">
{{category.name}}
<div ng-repeat="subcategory in category.subcategories | orderBy: '-value'">
{{subcategory.value}}
</div>
</div>