角度-是什么触发了2路数据绑定的摘要周期? [英] Angular - what triggers the digest cycle for 2 way data bindings?

查看:53
本文介绍了角度-是什么触发了2路数据绑定的摘要周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AngularJS如何实现2路数据绑定?模型更新的视图是可以理解的,即可以通过JS侦听器实现,但是我想了解模型以查看更新?由于Angular模型的核心是js变量,所以Angular如何监听js变量的变化?

How does AngularJS implements the 2-way data binding? The view to model update is understandable i.e. it can be achieved through the JS listeners but I wanted to understand the model to view update? As at the core angular models are js variables, so how does the Angular listen to the change in js vars?

我知道每个模型都有一个手表,它将新值与旧值进行比较,但是是什么触发了此检查(js实现)?

I know that each model has a watch which compare the new value with the old one but what triggers this check(the js implementation)?

它使用Javascript观察程序还是使用时间间隔进行检查?

Does it uses Javascripts watchers or a time interval for checking?

推荐答案

Angular定义了所谓的摘要循环的概念.这个周期可以 被视为一个循环,在此期间Angular检查是否存在任何循环 更改所有$ scopes监视的所有变量.所以如果你 在您的控制器中定义了$ scope.myVar,并且此变量是 标记为正在观看,则您明确告诉Angular 在循环的每次迭代中监视myVar上的更改.

Angular defines a concept of a so called digest cycle. This cycle can be considered as a loop, during which Angular checks if there are any changes to all the variables watched by all the $scopes. So if you have $scope.myVar defined in your controller and this variable was marked for being watched, then you are explicitly telling Angular to monitor the changes on myVar in each iteration of the loop.

基本上,AngularJS将事件处理程序绑定到与Angular进行交互的任何元素($scopedirective,...),每次事件触发时,都会调用$apply并在内部调用$digest,从而触发重新评估所有$watches.

Basically AngularJS binds event handlers to any element that interacts with Angular ($scope, directive, ...), every time the event fires, $apply is called which internally calls $digest which will trigger the re-evaluation of all the $watches.

AngularJS做出了聪明的假设,即模型更改仅在用户交互/事件上发生:

AngularJS made a smart assumption that model changes happen only on user interaction / events:

  • DOM事件
  • XHR响应触发回调
  • 浏览器的位置更改
  • 计时器(setTimout,setInterval)触发回调

或在某些events

  • 输入指令+ ngModel,ngClick,ngMouseOver等.
  • $ http和$ resource
  • $ location
  • $ timeout

当这些假设"之一被触发时,摘要周期开始:

要引用Pawel Kozlowski的话,

To quote Pawel Kozlowski, Mastering Web Application Development with AngularJS:

AngularJS不使用任何类型的轮询机制来定期 检查型号更改

AngularJS does not use any kind of polling mechanism to periodically check for model changes

更详细的见解

看看 https://www.youtube.com/watch?v=SYuc1oSjhgY 深入了解摘要周期.

Have a look at https://www.youtube.com/watch?v=SYuc1oSjhgY for a really deep dive into the digest cycle.

这篇关于角度-是什么触发了2路数据绑定的摘要周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆