Handling duplicate elements in an ng-repeat

angularjs, angularjs-ng-repeat, javascript

Solution

I'd like to add another answer to this question, because I discovered a simpler solution.

There's an important section of the documentation for `ng-repeat` which is easy to miss, specifically on the dupes error.

It states:

By default, collections are keyed by reference

After reading this, the solution was obvious - as I wasn't dealing with primitives (yes, the plunker is, but that was an over-simplification) I needed to copy the duplicate object and add its copy to the array. This means everything works as expected when you remove track by $index and just let the default behaviour take over.

Angular makes this especially easy because jqlite has a `.copy`. method.

Here's what I'm saying demonstrated in a plunker.

Problem

I am building an app which features a kind of "playlist". This is represented an ng-repeated custom directive with `ng-repeat = "element in playlist"` Because I want to allow a user to re-use the same element twice in the playlist, I tried using the `track by $index` addition. Now, what's confusing is: when I came to remove an element from the playlist (I have a function `removeElement(index)` which essentially contains something like this: ``` $scope.removeElement = function(index){ $scope.playlist.splice(index, 1); } ``` Something weird happened: the element was removed correctly from `$scope.playlist`, but for some reason the view didn't update properly. The last element appeared to be removed. Furthermore, I couldn't properly re-order the elements in the array either. When I removed `track by $index` this problem disappears, so I assume this is because when you remove an item from the array, if you're only looking at the indices, then it appears you've just deleted the last one. The behaviour is odd though, because transcluded content is correctly removed -- see this plunker EDIT: The above link has been modified to show the problem better and also show the answer I settled on. The question has also been slightly edited, to make it clearer what I was getting at. KayakDave's answer below is still correct, but is more suited to an array of primitives (which my original plunker featured). TL;DR: How do you put duplicate elements in an `ng-repeat` without sacrificing the ability to control their position, or remove elements correctly?

Original source