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.
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.
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];
});
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.