0

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.

1
  • 1
    Can you create a minimal reproducible example demonstrating the issue? This should work and the only reason I can think that your view is not updating is because you are pushing items onto the array outside of Angular's digest cycle. Commented Jan 9, 2019 at 23:48

2 Answers 2

1

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.

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

Comments

0

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.

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.