什么时候调用 $digest 循环? [英] when $digest cycle is called?

查看:26
本文介绍了什么时候调用 $digest 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当摘要循环发生时,我很困惑,它是否基于每 50 毫秒的计时器定期调用(正如它所说的 这里 和隐含的这里) 还是在每个进入 angular 上下文的事件之后调用它(正如它所说的 这里此处此处) ?

I'm very confused when a digest cycle is happening, is it called periodically based on a timer every 50ms (as it says here and implied here) or is it called after every event that enters the angular context (as it says here, here and here) ?

重要的例子:

在我的模型中,我有一个名为 myVar 的变量,其值为 3.在我的 HTML 中,我有 {{myvar}}.触发按钮单击等事件并在控制器中引发处理程序,处理程序内的代码为:

In my model, I have a variable called myVar with the value of 3. In my HTML, I have {{myvar}}. An event such as a button click is fired and raises a handler in the controller, the code inside the handler is:

$scope.myVar = 4;
// some heavy actions takes place for 3 seconds...
$scope.myVar = 5;

假设UI线程没有被阻塞,用户点击按钮后会看到什么?他会只看到 5 个,还是会看到 4 个,3 秒后看到 5 个?

Assuming the UI thread is not blocked, what will the user see after the button click? will he see only 5 or will he see 4 and after 3 seconds 5?

推荐答案

我认为 http://blog.bguiz.com/post/60397801810/digest-cycles-in-single-page-apps

间隔运行的代码

非常具有误导性,老实说,当提到 Angular 时,我什至会说错.引用 Pawel Kozlowski 的话,掌握使用AngularJS开发Web应用程序

is very misleading, and to be honest, when referring to Angular, I would even say wrong. 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

为了证明没有轮询,如果你有一个模板

To prove there is no polling, if you have a template of

<p>{{state}}</p>

$scope.state = 'Initial';
// Deliberately *not* using $timeout here
$window.setTimeout(function() {
  $scope.state = 'Changed';
},1000);

就像在这个plunker中,那么显示给用户的字符串将保持为Initialcode> 并且永远不会更改为 Changed.

as in this plunker, then the string shown to the user will remain as Initial and never change to Changed.

如果您想知道为什么经常看到对 $apply 的调用,但并非总是如此,这可能是因为 Angular 附带的各种指令,例如 ngClick或者 ngChange 会自己调用 $apply,然后触发循环.直接对原生 JS 事件的事件侦听器不会这样做,因此他们必须故意调用 $apply 以使所做的任何更改反映在模板中.

If you're wondering why you often see calls to $apply, but not always, it is probably because the various directives that come with Angular, such as ngClick or ngChange will call $apply themselves, which will then trigger the cycle. Event listeners to native JS events directly will not do this, so they will have to deliberately call $apply to have any changes made reflected in templates.

这篇关于什么时候调用 $digest 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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