Vahid Najafi
Vahid Najafi

Reputation: 5263

Angularjs for loop with ng-repeat strange issue

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.

Upvotes: 1

Views: 1942

Answers (4)

Ajay Singh
Ajay Singh

Reputation: 1281

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

Upvotes: 2

Radek Anuszewski
Radek Anuszewski

Reputation: 1910

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.

Upvotes: 1

Brandon
Brandon

Reputation: 1827

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 = [];

Upvotes: 2

Thierry
Thierry

Reputation: 5243

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.

Upvotes: 1

Related Questions