问题描述
当我通过 Angular 应用程序中的 websockets 接收数据时,我一直在使用 $scope.$apply()
来更新我的模型的绑定并且它工作正常.但是它实际上是做什么的,为什么需要调用它来实现更新?
I've been using $scope.$apply()
to update the bindings for my models when I receive data through websockets in my Angular apps and it works. But what does it actually do and why does it need to be called to achieve the update?
推荐答案
来自 Angular文档:
$apply() 用于从外部执行 angular 表达式角度框架.(例如来自浏览器 DOM 事件,setTimeout、XHR 或第三方库).因为我们正在呼唤我们需要执行适当的范围生命周期的角度框架异常处理,执行观察.
文档还提供了它的伪代码:
The documentation also provides a pseudo-code of it:
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
简而言之,$apply
对表达式求值并触发摘要循环,使 Angular 执行所有已注册的监视侦听器并更新所有视图绑定.
In short, $apply
evaluates an expression and triggers a digest cycle, making Angular execute all registered watch listeners and update any view bindings.
最后,您已经说过您一直在使用 $apply
来更新模型的绑定,但这仅在更新来自 Angular 外部时才需要.在大多数情况下,您不需要手动调用它.
Finally, you've said that you've been using $apply
to update the bindings for your models, but that is only required when the update comes from outside Angular. In most cases you don't need to call it manually.
这篇关于$scope.$apply() 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!