How to display duplicate items using AngularJS ng-repeater


If you have a list of duplicate items and you want to display them using ng-repeater you get the following error.

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys.

As mentioned in the error message that you can use track by expression to solve the problem. Here is a small code snippet showing how to use track by expression.

AngularJS

(function () {
   'use strict';

   angular
      .module('app', [])
      .controller('DemoController', DemoController);

      function DemoController (){
         var vm = this;
         vm.items = ['Black', 'White', 'Red', 'Green', 'Blue', 'White'];
      } 

})();

HTML

<!DOCTYPE html>
<html lang="en-US">
<body ng-app="app">

<div ng-controller="DemoController as vm">
    <ul>
      <li ng-repeat="item in vm.items track by $index">{{item}}</li>
   </ul> 
</div>

<script src="angular.min.js"></script>
<script src="app.js"></script>

</body>
</html>

Output

Black
White
Red
Green
Blue
White

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments