Search code examples
angularjsangularjs-directiveangularjs-ng-repeathtml-lists

Angularjs ng-repeat doesn't show duplicate values in the list, but only the different ones


This code displays the contents of the text box in a list, via the ng-repeat directive. But I noticed that it doesn't show the duplicate letters. The letters are only shown if they are all different. For example, if I type abcabc in the text box, I see abc only once in the list, and not abcabc How can I also show duplicate letters? Thank you.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app>
  <input type="text" ng-model="names">
  <ul>
    <li ng-repeat="x in names">
      {{ x }}
    </li>
  </ul>
</div>


Solution

  • Whenever something breaks like this, always check the console. You get errors there because AngularJS expects all values to be unique. But obviously, they aren't. You can use track by to give the elements a unique identifier, in this case I used track by $index to make them use their index in the string.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
    <div ng-app>
      <input type="text" ng-model="names">
      <ul>
        <li ng-repeat="x in names track by $index">
          {{ x }}
        </li>
      </ul>
    </div>