【发布时间】:2015-05-11 03:37:54
【问题描述】:
我有一个案例,我需要重复来自各种 ajax 源的结果。我不能等待所有源在渲染之前加载,我必须在结果进入时渲染它们。但我希望结果按特定顺序排列(按字母顺序排列)。如果所有结果同时出现,ngRepeat 会相应地对它们进行排序,但如果它们是异步加载的,则不会。
加载完所有结果后,如何对重复进行重新排序?
我创建了一个plunkr here 来模拟异步 ajax 和我得到的乱序结果。
这是我正在做的一个过于简化、有点做作的示例(仅用于说明目的,因为 SO 需要代码)。
// ngRepeat over $scope.prices in correct order
// all ajax loaded then $scope.prices assigned
var priority = ['1 Day', '3 Day', 'Ground'];
var prices = {};
for(var i = 0; i < priority.length; ++i) {
$http.get('some/endpoint/' + priority[i])
.then(function(response) {
prices[priority[i]] = response.data;
});
}
$scope.prices = {
'1 Day': prices['1 Day'],
'3 Day': prices['3 Day'],
'Ground': prices['Ground']
};
// ngRepeat over $scope.prices in order of successful load
// $scope.prices keys assigned as results are available
var priority = ['1 Day', '3 Day', 'Ground'];
for(var i = 0; i < priority.length; ++i) {
$http.get('some/endpoint/' + priority[i])
.then(function(response) {
$scope.prices[priority[i]] = response.data;
});
}
【问题讨论】:
标签: javascript angularjs sorting angularjs-ng-repeat