1

I have a case where I need to repeat over results from various ajax sources. I can't wait for all sources to load before rendering, I must render the results as they come in. But I want the results to be in a particular order (alphabetical as it so happens). ngRepeat sorts them accordingly if all results are present at the same time, but not if they are loaded asynchronously.

How can I re-sort the repeat after all the results are loaded?

I've created a plunkr here to simulate the async ajax and the out of order results I get.

Here is an overly simplified, somewhat contrived sample of what I'm doing (for illustration purposes only, because SO requires code).

// 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;
    });
}

2 Answers 2

1

In your main.html, you can make use of the orderBy function provided by angular

    <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>

this will take the array as it comes in and sorts the output

Sign up to request clarification or add additional context in comments.

1 Comment

It's not the rates ordering I'm concerned with, it's the actual order of the priorities themselves, i.e. I want to the order to be 1 Day, 3 Day, Ground, regardless of when those results arrive.
0

Could you use order and apply a value for each price object's (1 day, 2 day, ground), etc.. ?

As far as the render, could you have the ng-repeat refresh on-click when you update the list, and possibly apply a fade in / out?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.