user95227
user95227

Reputation: 1963

ng-repeat not working consistently with arrays of items

I have two arrays of strings that I want to repeat within my page. Here are the arrays (infoData and modelData) in the debugger:

Screenshot of arrays in Chrome inspector:

screenshot

Here is my html:

<div ng-repeat="info in pTab.infoData">
    <p>{{info}}</p>
</div>

<div ng-repeat="stats in pTab.modelData">  
    <p>{{stats}}</p>
</div>

However the page only displays the contents of infoData as shown below:

XPE

www.sampleurl.com

Sample summary has nulla quis lorem ut libero malesuada feugiat...

My question is why does this happen and how can I get the elements of the second array to display like the first?

Here is some additional info that may be useful to you. As I was trying out different things this struck me as interesting:

The following HTML:

<div ng-repeat="info in pTab.infoData">
    <p>{{pTab.infoData}}</p>
</div>

<div ng-repeat="stats in pTab.modelData">  
    <p>{{pTab.modelData}}</p>
</div>

displays the infoData array in square brackets as a string 3 times (infoData has a length of 3).While the following HTML:

<div ng-repeat="info in pTab.infoData">
    <p>{{pTab.modelData}}</p>
</div>

<div ng-repeat="stats in pTab.modelData">  
    <p>{{pTab.infoData}}</p>
</div>

displays the modelData array in square brackets as a string 3 times.

Is there something wrong with the <div ng-repeat="stats in pTab.modelData">? Because whatever is in that div never repeats, even if I move that div ahead of the <div ng-repeat="stats in pTab.modelData">

If I'm being unclear or you'd like to see more of the code, please let me know. Thank you very much for your time.

Upvotes: 0

Views: 258

Answers (1)

Grundy
Grundy

Reputation: 13381

If you look in browser console you can see error like this

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: stats in pTab.modelData, Duplicate key: string:0.1 mg, Duplicate value: 0.1 mg

So, you have duplicated items in your second array, and for resolve this error should use track by expression, in this case enough $index

<div ng-repeat="stats in pTab.modelData track by $index">  

A bit more about it you can see in doc: Tracking and Duplicates

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.pTab = {
      modelData: [
        '0.1 mg',
        '0.1 mg',
        '0.1 mg'
      ]
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller='ctrl'>
  <h1>Hello Plunker!</h1>
  <div ng-repeat="stats in pTab.modelData track by $index">
    <p>{{stats}}</p>
  </div>
</div>

Upvotes: 1

Related Questions