Reputation: 63
I've read in another stack overflow post that angular.js tries to be smart when the collection used in ng-repeat changes so that the DOM is not rebuilt completely (see Does ng-repeat retain DOM elements or create all new ones when the collection changes?). However I'm experiencing a problem: When I remove one item from my collection, all items following this one are rebuilt in the DOM. This is problematic for me because I am listing for the jQuery remove event and this event gets fired multiple times, although only one item got removed. Listening for scope.$on('remove')
could solve my problem - this gets only triggered once - but here is my problem, that I want to access jQuery data
before removing and when scope.$on('remove')
is triggered, data
got already removed.
What can I do to solve this issue? See this link for a demo: http://plnkr.co/edit/T1ZicU20JjWYk1J5ch7Z?p=preview.
element.bind('remove', function() {
alert("Element remove handler called.");
});
When I remove the third element, remove gets already triggered once, when I remove the second one, it gets triggered twice, when removing the third one, it gets triggered thrice.
Upvotes: 3
Views: 2219
Reputation: 5766
Just add the track by
to solve this issue :
ng-repeat="w in widgets track by $index"
Explanation:
When you add track by
you basically tell angular to generate a single DOM element per data object in the given collection. This could be useful when paging and filtering, or any case where objects are added or removed from ng-repeat
list.
Reference: http://www.bennadel.com/blog/2556-using-track-by-with-ngrepeat-in-angularjs-1-2.htm
Upvotes: 2