1

I have a simple array and a ng-repeat :

<p ng-repeat="person in persons">
  Hello {{person}}!
</p>

But when I generate it with for loop, the result is very strange! The ng-repeat doesn't print in order. See codepen.

4 Answers 4

2

In your JS (on code pen) you have:

$scope.persons = {};
for (var i = 0; i < 20; i++) {
    console.log(i);
    $scope.persons[i] = i;
}

You are initiating persons as an object. Change to $scope.persons = [];

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

Comments

2
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.persons = [];
  for (var i = 0; i < 20; i++) {
            console.log(i);
            $scope.persons[i] = i;
       $scope.results = angular.toJson($scope.persons)
        }

  //$scope.persons = [1, 2, 3, 4, 5];
});

https://codepen.io/anon/pen/rmVaZV?editors=1111

Comments

1

ng-repeat for objects {} itself does not provide displaying with order (in most cases elements have order, but not in 100%) - in case of object, key is String, so they are ordered as string (["1", "11", "2"]) - but JS at all does not preserve order of {}, so even if they are displayed in any order, someday it may break without any big reason (browser update etc). Just use Array which are ordered, where sort is more natural (keys are number), check Codepen: https://codepen.io/anon/pen/mmJyGX Or use orderBy with additional field, like id. My advice is, if you care about order, always use [] instead of {}, cause it always will work as expected.

Comments

1

With a recent version of angular (1.6.0 for example), it doesn't happen. You use an old version (1.1.5), it seems that this version sort by default the array.

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.