Angular 生成重复的倍数

Angular generating multiple ng-repeats

在我的 angular 应用程序 (angular 1.4.9) 中,我遇到了一个问题,当我这样做时会生成多个 ng-repeats:

HTML:

<div class="form-group col-md-3">
  <input ng-model="main.startLocation" ng-change="main.getAddressSuggestions(main.startLocation, 'startLocation')" type="text" class="form-control input-lg" placeholder="fx. Aarhus" tabindex=1 name="country" [![enter image description here][1]][1] />

  <label>or select a location from list:</label>
  <div ng-repeat="suggestion in main.startLocationSuggestions">
    <span>{{suggestion}}</span>
  </div>

</div>

controller.js

getAddressSuggestions(address, inputName) {
  if (inputName === "startLocation") {

    /*                  var tmpArray = data;
     for(var item of tmpArray)
     this.startLocationSuggestions = data;*/
    this.startLocationSuggestions = ['dada', 'daa'];
  }
}

但是在dom中生成的HTML是:

为什么 angular 重复 ng-repeats?

这基本上就是 ng-repeat 的工作原理! 一开始它写了一条评论:

<!-- ngRepeat: x in items -->

然后对于每个用 ng-repeat 创建的元素,在创建它之后(内部有 ng-repeat 属性),写另一个注释:

<!-- end ngRepeat: x in items -->

因为它只是把你的模板照原样(div ng-repeate lalala),克隆它N次,填充数据并放入DOM。

如果不想重复父元素,这里是html:

<div >
  <span ng-repeat="suggestion in startLocationSuggestions">{{suggestion}}</span>
</div>

输出将是:

<div>
  <!-- ngRepeat: suggestion in startLocationSuggestions -->
  <span ng-repeat="suggestion in startLocationSuggestions" class="ng-scope ng-binding">dada</span>
  <span ng-repeat="suggestion in startLocationSuggestions" class="ng-scope ng-binding">daa</span>
</div>

这就是 ngRepeat 的工作原理。