什么是$范围。$适用()呢? [英] What does $scope.$apply() do?

查看:107
本文介绍了什么是$范围。$适用()呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 $范围。$适用()来更新我的模型绑定,当我经过的WebSockets在我的角度应用接收数据和它的作品。但什么是它实际上做的,为什么它需要被调用来实现更新?

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?

推荐答案

角文档

$申请()用于从外侧角来执行一个前pression
  角框架。 (例如,从浏览器的DOM事件,
  setTimeout的,XHR或第三方库)。因为我们是调用到
  角框架我们需要执行的适当范围的生命周期
  异常处理,执行手表。

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life-cycle of exception handling, executing watches.

该文档还提供了它的伪code:

The documentation also provides a pseudo-code of it:

function $apply(expr) {
  try {
    return $eval(expr);
  } catch (e) {
    $exceptionHandler(e);
  } finally {
    $root.$digest();
  }
}

在短, $适用计算一个前pression并触发消化周期,使得角执行所有注册的手表听众和更新任何视图绑定。

In short, $apply evaluates an expression and triggers a digest cycle, making Angular execute all registered watch listeners and update any view bindings.

最后,你说你一直在使用 $适用来更新你的模型绑定,但是当更新来自外部的角度时,才需要。在大多数情况下,你不需要手动调用它。

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.

这篇关于什么是$范围。$适用()呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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