ng-sortable
ng-sortable copied to clipboard
Incorrect reordering when using track by $index
Elements get randomly reordered after a drag when using "track by $index"
I'm using "track by $index" because my list have dupes that are not allowed in an ng-repeat, you can check it out here: http://plnkr.co/edit/iVEdhGNFbWkwgwTI5oG7?p=preview
+1. I ran into it also. but it's not reorder, or add one more item in model
It also has a weird behavior when using orderBy:'value'. Some help?
Thanks
For the problem with "track by", you can define your own "track by" function :
$scope.UniqueTracking = function(index, id){
return index + id
}
and use it like this :
ng-repeat="(itemNb, item) in items track by UniqueTracking(itemNb, item.id)"
That works perfectly! Thanks @pfouque
I modified the plnkr with your solution, not sure if I should close the issue or if this can be somehow be built into ng-sortable. (@a5hik) Sample with fix: http://plnkr.co/edit/l93UJLmLHhjweLVPGORb?p=preview
Great work @pfouque. Haven't come across that trick before. Had to modify the function to return a random unique id but you've saved me a few hours I feel! Thanks!
I have the same problem , thank you @pfouque
+1 for @pfouque's solution, hopefully the directive itself can be patched.
You can add a dash or something to split the id and index, in case the id is also a number . If not you may still get an issue if you have sums that end up the same. ie (index 0 + id 4) is the same as (1 index + id 3)
Addition to @pfouque 's answer, you don't really have to use a new function. You can just do the operation inline;
ng-repeat="item in items track by $index + item"
I'm guessing, This works because we are creating a new uniq id other than $index which is probably keep overlaping while the order is changing by ng-sortable.
I've been struggling with this one for a while and just now discovered that there is a solution built into the module by @a5hik. For me, the problem is that I wanted to allow duplicate items and it would clean them up and remove them even when I was properly setting a unique ID instead of $index
. Simply enabling allowDuplicates
in conjunction with a unique hash instead of $index
was ultimately the fix.
$scope.dragControlListeners = {
allowDuplicates: true //optional param allows duplicates to be dropped.
};
<div as-sortable="dragControlListeners">