角$范围。$消化VS $范围。$申请 [英] Angular $scope.$digest vs $scope.$apply

查看:100
本文介绍了角$范围。$消化VS $范围。$申请的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道热使用 $消化。内部控制器以下code正常工作,并在3秒后更新DOM:

I just want to know hot to use $digest. Inside a controller the following code works fine and it updates the DOM after 3 seconds:

setTimeout(function(){
    $scope.$apply(function(){
    $scope.name = 'Alice';
    });
},3000);

不过用

setTimeout(function(){
        $scope.$digest(function(){
        $scope.name = 'Alice';
        });
    },3000);

什么也没有发生......

nothing happens...

我认为他们做同样的事情。在什么我错了?

I thought that they do the same thing. In what am I wrong?

推荐答案

$适用() $消化()有一定的相似性和差异。它们是相似的,它们都检查什么变化和更新UI和火的观察家。

$apply() and $digest() have some similarities and differences. They are similar in that they both check what's changed and update the UI and fire any watchers.

两者之间的一个区别是它们是如何调用。 $消化()被称为不带任何参数。 $适用()需要,它会做任何更新之前执行的功能。

One difference between the two is how they are called. $digest() gets called without any arguments. $apply() takes a function that it will execute before doing any updates.

另一个区别是它们影响什么。 $消化()将更新目前的范围和任何子范围。 $适用()将更新所有的范围。所以大部分的时间 $消化()将是你想要什么,更高效。

The other difference is what they affect. $digest() will update the current scope and any child scopes. $apply() will update every scope. So most of the time $digest() will be what you want and more efficient.

这也是为什么 $申请最后的区别()需要一个功能是它们如何处理观察家异常。 $适用()将通过例外 $ exceptionHandler的,而 $讯()会要求你自己处理的异常。

The final difference which explains why $apply() takes a function is how they handle exceptions in watchers. $apply() will pass the exceptions to $exceptionHandler, while $dispatch() will require you handle the exceptions yourself.

这篇关于角$范围。$消化VS $范围。$申请的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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