gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:58:38 25 4
gpt4 key购买 nike

我已经看到了很多关于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com