javascript - 为什么这个 ng-repeat 不循环所有的值?

标签 javascript angularjs ionic-framework

更多的值被插入数组:

.controller('MyCtrl', function($scope) {

  $scope.mottos = [];
  $scope.mottos.push('One');
  $scope.mottos.push('Two');

  $scope.addMotto = function(motto) {
    $scope.mottos.push(motto);
  }    
});

<span ng-repeat="motto in mottos"> {{motto}} </span>   

ng-repeat 没有按预期显示所有元素:codepen , 为什么? ...

HTML

<ion-content>

    <button class="button button-positive" ng-click="addMotto('More')">
      <i class="icon ion-quote"> Click me to add more ...</i>
    </button>

    <div class="card item-text-wrap">
     <div class="item">
      {{mottos.length}}
      <span ng-repeat="motto in mottos"> {{motto}} </span>
     </div>
    </div>

</ion-content>

最佳答案

来自documentation :

By default, ngRepeat does not allow duplicate items in arrays. This is because when there are duplicates, it is not possible to maintain a one-to-one mapping between collection items and DOM elements.

If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression.

因此,如果您按如下方式更新代码,一切都会按预期工作:

<span ng-repeat="motto in mottos track by $index">
    {{motto}}
</span>

关于javascript - 为什么这个 ng-repeat 不循环所有的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30794484/

相关文章:

javascript - 弹出窗口在向下滚动时更改位置

javascript - 根据angularJS中的另一个输入[type=text]值设置输入[type=range]最大值

android - Cordova hideKeyboardAccessoryBar 不工作

javascript - 如何在不使用 Twitter API 1.1 的情况下检索 Twitter user_timeline

javascript - 使用纯 JavaScript 或 Lodash 进行 JSON 数组操作

javascript - Ad Hoc Javascript 库返回未定义

javascript - 基于属性的 Angular Directive(指令)模板变量

javascript - 使用 angularJs 未在模态中显示正确的信息

javascript - angularjs指令错误:[nonassign]

android - Ionic - 应用程序没有足够的地理定位权限