How does AngularJS's $watch function work?
I'm reading a lot about AngularJS nowadays, and I came across that magical $watch function. I understand how to use it, but I wonder how is it implemented in the background. Is it a time interval function? Or is it Angular calling this watch every statement executed?
I don't want to dig into the source code right now, and I would glad if one of you already know the answer and want to share his knowledge about the subject.
Thanks.
All watches are evaluated (sometimes multiple times) every digest loop. The digest loop is entered as a result of some event, or calling $apply(). Watches are not called periodically based on a timer.
See 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.
链接地址: http://www.djcxy.com/p/23136.html上一篇: Android活动/片段负责数据加载