通过改变从“外部”的角度JS服务的观察家停止工作 [英] by changing a service from 'outside' angular js the watchers stop working
问题描述
我这样做的:
angular.element('body').injector().get("myService").somevar = true
和别的地方我抓住它:
$scope.$watch( function () { return myService.somevar; }, function (somevar) {
console.log(somevar)
});
但观察者不会触发,即使如果我通过控制台检查值它实际上已经改变了
But the watcher does not trigger, even though if i check the value through the console it has in fact changed
推荐答案
正如前面提到的,你需要使用的 $适用:
As already mentioned, you need to use $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.
例如:
var element = angular.element(document.querySelector('body'));
var service = element.injector().get('myService');
var scope = element.scope();
scope.$apply(function () {
service.somevar = true;
});
演示: http://plnkr.co/编辑/ Iy3CiRzDdxFTwVq68JWi?p = preVIEW
这篇关于通过改变从“外部”的角度JS服务的观察家停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!