javascript - AngularJS $watch 函数如何工作?

标签 javascript angularjs angularjs-scope

我现在阅读了很多关于 AngularJS 的资料,并且遇到了那个神奇的 $watch 函数。我知道如何使用它,但我想知道它是如何在后台实现的。是时间间隔函数吗?还是 Angular 会在执行的每个语句中调用这个 watch?

我现在不想深入研究源代码,如果你们中有人已经知道答案并想分享他对这个主题的知识,我会很高兴。

谢谢。

最佳答案

所有 watch 在每个摘要循环中都会被评估(有时多次)。由于某些事件或调用 $apply() 而进入摘要循环。 watch 不会根据计时器定期调用。

参见 https://docs.angularjs.org/guide/scope#integration-with-the-browser-event-loop

The browser's event-loop waits for an event to arrive. The event's callback gets executed... Once the callback executes, the browser leaves the JavaScript context and re-renders the view based on DOM changes. Angular modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and Angular execution context... Angular executes [some] stimulusFn(), which typically modifies application state. Angular enters the $digest loop. The loop is made up of two smaller loops which process $evalAsync queue and the $watch list. The $digest loop keeps iterating until the model stabilizes, which means that the $evalAsync queue is empty and the $watch list does not detect any changes. The $watch list is a set of expressions which may have changed since last iteration. If a change is detected then the $watch function is called which typically updates the DOM with the new value.

enter image description here

关于javascript - AngularJS $watch 函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18634666/

相关文章:

javascript - 其他指令(如 ng-init)或事件(如 stateChangeStart)会触发特定路由

javascript - 返回对象之前等待所有回调完成

javascript - `HTMLElement` 和 `Element` 有什么区别?

javascript - 在 React 中切换嵌套状态对象

angularjs - $compile 正在为 Angular 表达式评估字符串之前加载图像

angularjs - 如何从 Angular 指令取回数据

javascript - jQuery 插件中忽略的 setTimeout 时间间隔

html - 无法使用选择输入 + AngularJS 禁用语义 UI 下拉列表

javascript - 更改元素的类 onkeyup

javascript - 键盘显示时 Ionic ion-content 不向下滚动 (Android)