角度 $scope.$digest 与 $scope.$apply [英] Angular $scope.$digest vs $scope.$apply

查看:18
本文介绍了角度 $scope.$digest 与 $scope.$apply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道如何使用$digest.在控制器内部,以下代码运行良好,3 秒后更新 DOM:

I just want to know how 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);

什么都没发生...

我认为他们做同样的事情.我错了吗?

I thought that they do the same thing. Am I wrong?

推荐答案

$apply()$digest() 有一些异同.它们的相似之处在于它们都检查更改的内容并更新 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.

两者之间的一个区别是它们的调用方式.$digest() 在没有任何参数的情况下被调用.$apply() 接受一个函数,它将在执行任何更新之前执行.

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.

另一个区别是它们的影响.$digest() 将更新当前作用域和任何子作用域.$apply() 将更新每个范围.所以大多数情况下 $digest() 将是您想要的并且更高效.

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.

解释为什么 $apply() 需要一个函数的最后一个区别是它们如何处理观察者中的异常.$apply() 会将异常传递给 $exceptionHandler(内部使用 try-catch 块),而 $digest() 将要求您处理自己的例外.

The final difference which explains why $apply() takes a function is how they handle exceptions in watchers. $apply() will pass the exceptions to $exceptionHandler (uses try-catch block internally), while $digest() will require you handle the exceptions yourself.

这篇关于角度 $scope.$digest 与 $scope.$apply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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