2

Let's say I have an array of objects and that each object has a unique ID and a text property.

Now, let's say I have a ng-repeat like this one:

Controller

$scope.data = my_arr;

View

<div ng-repeat="for elem in data track by elem.id">
    {{ elem.text }}
</div>

Special note on the track by.

What would happen if I assigned a completely new array to the data variable ($scope.data = new_arr;), if the content of this new array:

  • is completely identical to the previous one
  • it contains 1 new element
  • it contais all elements except 1

Will AngularJS be smart enough to:

  • not re-render all div elements
  • append/insert only the new div element to the DOM
  • hide/delete only the div that isn't contained in the new array
2
  • Should the ng-repeat expression be "for elem in data track by elem.id"? Commented Feb 8, 2016 at 10:20
  • @slbteam08 Ah, yes, that is a typo, let me fix it. Commented Feb 8, 2016 at 10:21

1 Answer 1

1

Since you’re using track by elem.id, Angular will reuse DOM elements. It will only add or remove one element to the document tree. Per the docs:

Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

Sign up to request clarification or add additional context in comments.

7 Comments

Yes, I'm concerned about this part: if the JavaScript objects in the collection have been substituted for new ones.. The thing is that this makes sense when you pull/push items from the same collection, but what would happen if the entire collection is changed? Hence, $scope.data = new_arr;
ngRepeat will check for matching ids and move / remove elements if needed, but will not remove an element then add it again for the same id.
Do you happen to know how could I test the rendering speed of ng-repeat (or pretty much any angular directive)?
And by "rendering speed" I mean the amount of time it takes from Angular detecting a change in the data set to the last operation related to actual rendering/DOM modifying.
I guess you could use Chrome Devtools to do this: addyosmani.com/blog/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.