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

时间:2019-01-09 22:37:01

标签: html angularjs

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.

2 个答案:

答案 0 :(得分:1)

很高兴地知道您在什么时候执行此$ scope项目人口,考虑到摘要循环的工作原理。无论您如何填充数组,以下都是有效的方法:

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>

这通过使用$ scope.items并在实例化Controller时从HTML访问它来工作。尽管如此,我还是建议采用以下更清洁的方法:

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>

这里的主要区别是您不会污染$ scope对象(甚至没有注入它),而是在控制器的实例中创建一个属性。

请记住,知道何时以及如何进行数组填充非常重要,因为AngularJ的摘要循环以独特的方式工作。

我希望这会有所帮助。

答案 1 :(得分:0)

感谢大家的帮助。我正在注入$ scope并正确使用它。我的问题是我的阵列不时有重复的条目。将我的HTML更改为

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

解决了该问题。