我有两个关于它如何工作的想法.
第一种方式:
当ng-repeat的观察者触发时,它会删除它从DOM创建的所有元素,然后在其位置创建所有新元素,即使这些元素中的许多元素相同(例如,在将1个项目添加到后备阵列的情况下).
第二种方式:由于ng-repeat已经跟踪哪些元素与其后备集合中的哪些项目相关,因此它只删除集合中不再存在的项目,并为集合中新增的项目创建新元素.
这是为什么?为什么?
The
ngRepeat
directive provides a way to render a collection of items given a template. To do this,AngularJS compiles the given template and then clones it for each unique item in the collection. As the collection is mutated by the Controller,AngularJS adds,removes,and updates the relevant DOM elements as needed.But,how does AngularJS know which actions to perform when? If you start to test the rendering,you’ll discover that AngularJS doesn’t brute force DOM creation; that is,it doesn’t recreate the DOM for every rendering. Instead,it only creates a new DOM element when a completely new item has been introduced to the collection. If an existing item has been updated,AngularJS merely updates the relevant DOM properties rather than creating a new DOM node.
这仍然会不必要地影响性能,即在集合中传递元素按值时(在上面链接的博客文章中有一个很好的例子).这就是为什么Angular supports “track by” for ngRepeat从版本1.2开始:这是一种帮助Angular决定何时创建DOM的方法:
With this association in place,AngularJS will not $destroy and re-create DOM nodes unnecessarily. This can have a huge performance and user experience benefit.
You can also provide an optional tracking function which can be used to associate the objects in the collection with the DOM elements. If no tracking function is specified the ng-repeat associates elements by identity in the collection.
For example:
item in items track by item.id
is a typical pattern when the items come from the database. In this case the object identity does not matter. Two objects are considered equivalent as long as their id property is same.