Phil O
Phil O

Reputation: 1668

ng-repeat does not work if I populate my array using push

ng-repeat works if I create a static array but not if I create the array dynamically.

HTML

<div ng-repeat="item in items">{{ item }}</div>

Code that populates the array and renders what I expect in the HTML

$scope.items = ["a", "b", "c"];

Code that populates the array but renders nothing in the HTML

$scope.items = [];
$scope.items.push("a"); 
$scope.items.push("b");
$scope.items.push("c");

I should add that when I look at the array in the debugger $scope.items contains the 3 values. It just doesn't render in the HTML.

Upvotes: 0

Views: 218

Answers (2)

Phil O
Phil O

Reputation: 1668

Thanks for everyone's help. I was injecting $scope and using it properly. My issue was that every now and then my array had duplicate entries in it. Changing my HTML to

<div ng-repeat="item in items track by $index">{{ item}}</div>

fixed the issue.

Upvotes: 0

wilsotobianco
wilsotobianco

Reputation: 1558

It would be nice to know in what moment are you performing this $scope items population considering how the digest cycle works. The following is something that works no matter how you populate the array:

angular.module('app', [])

angular.module('app').controller('DemoController', ['$scope', function($scope) {
  $scope.items = [];
  
  $scope.items.push(1);
  $scope.items.push(2);
  $scope.items.push(3);
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>

<section ng-app="app" ng-controller="DemoController as ctrl">
  <div ng-repeat="item in items">{{item}}</div>
</section>

This works by using the $scope.items and accessing it from the HTML when the Controller gets instantiated. Nevertheless I would recommend the following cleaner approach:

angular.module('app', [])

angular.module('app').controller('DemoController', function() {
  this.items = [];
  
  this.items.push(1);
  this.items.push(2);
  this.items.push(3);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>
<section ng-app="app" ng-controller="DemoController as ctrl">
  <div ng-repeat="item in ctrl.items">{{item}}</div>
</section>

The main difference here is that you're not polluting the $scope object (it's not even injected) but creating a property in the controller's instance.

Keep in mind that's very important to know when and how you're doing the population of the array because AngularJs digest cycle works in a peculiar way.

I hope this helped.

Upvotes: 1

Related Questions