AngularJS和的WebSockets:回调函数需要$ $范围适用于()工作 [英] AngularJS and WebSockets: Callback function needs $scope.$apply() to work

查看:134
本文介绍了AngularJS和的WebSockets:回调函数需要$ $范围适用于()工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AngularJS和电话网络服务要通过WebSockets的电话。结果
Web服务有几个回调,如 Phone.onIncomingCall

I am using AngularJS and a phone web service to make calls through WebSockets.
The web service has several callbacks such as Phone.onIncomingCall

当我使用这个功能设置 $范围变量视图不会自动更新,除非我用 $范围。$适用右后。

When I use this function to set a $scope variable the view is not updated automatically except if I use $scope.$apply right after.

Phone.onIncomingCall = function(){
  $scope.myVar = "newValue";
  $scope.$apply(); // only works if I call this line
};

什么是原因行为(是否预期),是有办法解决使用方法 $ scope.apply()中的每个函数?

What is the reason for this behaviour (is it expected) and is there a way around using $scope.apply() in each function?

推荐答案

角是更新您所做的作用域变量的不知道,因为你从角背景之外更新它。从文档的 $适用

Angular is "unaware" of the update to the scope variable you've made, since you're updating it from outside of the Angular context. From the docs for $apply:

$申请()用于从外侧角来执行一个前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.

通过运行 $适用的范围, $消化从名为 $ rootScope ,这将触发 $ scope.myVar 注册的 $观看器。在这种情况下,如果您使用的是通过插值视图变量,这哪里是 $观看从登记呃。

By running $apply on the scope, $digest is called from $rootScope, which will trigger any $watchers registered on $scope.myVar. In this case, if you're using the variable in your view via interpolation, this is where the $watcher was registered from.

这篇关于AngularJS和的WebSockets:回调函数需要$ $范围适用于()工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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