Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this ng-repeat does not loop all the values?

Even more values are pushed into the array:

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

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

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

and

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

ng-repeat does not show all elements as expect: codepen, why? ...

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>
like image 816
ohho Avatar asked Apr 15 '26 22:04

ohho


2 Answers

From the 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.

So if you update your code as follows, things work as expected:

<span ng-repeat="motto in mottos track by $index">
    {{motto}}
</span>
like image 194
Robby Cornelissen Avatar answered Apr 18 '26 10:04

Robby Cornelissen


Instead of this

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

try something like this

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

you can see this in more detail on this page

like image 32
chiragchavda.ks Avatar answered Apr 18 '26 10:04

chiragchavda.ks