【问题标题】:re-sort angularjs ngRepeat with subsequent data results使用后续数据结果重新排序 angularjs ngRepeat
【发布时间】: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


    【解决方案1】:

    在你的main.html中,你可以使用angular提供的orderBy函数

        <ul>
      <li ng-repeat="(priority, rates) in prices">
        <h2>{{priority}}</h2>
        <ul>
          <li ng-repeat="prices in rates | orderBy:'price'">{{prices.price}}</li>
        </ul>
      </li>
    </ul>
    

    这将获取传入的数组并对输出进行排序

    【讨论】:

    • 这不是我关心的费率排序,而是优先级本身的实际顺序,即我希望顺序为 1 天、3 天、地面,无论这些结果何时到达.
    【解决方案2】:

    您能否使用 order 并为每个价格对象(1 天、2 天、地面)等应用一个值。

    就渲染而言,您能否在更新列表时单击 ng-repeat 刷新,并可能应用淡入/淡出?

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 2018-06-01
      • 2017-05-13
      • 1970-01-01
      • 2018-09-27
      • 2018-07-24
      相关资源
      最近更新 更多