angularjs - 当集合更改时,ng-repeat 是保留 DOM 元素还是创建所有新元素?

标签 angularjs angularjs-ng-repeat

我已经看到了很多关于 ng-repeat 完成顺序的问题,与其他指令或 Angular 领域中发生的事情相比,但我一直无法找到它究竟是如何实现这一点的答案。

我有两个关于它如何工作的想法。

第一种方式:
当 ng-repeat 的 watcher 触发时,它会删除它从 DOM 中创建的所有元素,然后在它们的位置创建所有新元素,即使这些元素中有许多是相同的(例如,在将 1 个项目添加到支持数组的情况下)。

第二种方式:由于 ng-repeat 已经跟踪了哪些元素与它的后备集合中的哪些项对应,它只是删除集合中不再存在的项,并为集合中的新项创建新元素。

它是哪个,为什么?

最佳答案

这是第二种方式: Angular tries to be smart about creating/removing DOM elements :

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.


官方文档states :

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.

关于angularjs - 当集合更改时,ng-repeat 是保留 DOM 元素还是创建所有新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23766534/

相关文章:

javascript - 单击后悬停状态卡在按钮上

javascript - 使用 AngularJS 的动态元图像

javascript - 如何在 AngularJs 中将增加的值重置为其初始值

javascript - AngularJS 不显示 ng-repeat,只显示一个空列表

angularjs - 什么是 Angular 态?

javascript - AngularJS 工厂

angularjs - 使用 ng-Style 更改背景颜色

html - 使用 Angularjs 每表行重复表单

javascript - 使用单选按钮重复 ng 时出现错误

javascript - 使用 angularjs 的图库弹出窗口不起作用,但使用 javascript 工作正常