简体   繁体   English

如何将对象包装在angularjs服务中(并观察该对象的更改)?

[英]How do I wrap an object in an angularjs service (and watch this object for changes)?

I'm wondering how I would go about watching a Javascript object for changes if that object isn't "a part of angular". 我想知道如果该对象不是“角度的一部分”,我将如何去观察它的变化。 So for instance I have a module, lets call it watchModule, that is directly accessible in the window. 因此,例如,我有一个模块,可以将其命名为watchModule,该模块可在窗口中直接访问。 What i'm doing right now (and i'm sure is wrong, which is why I'm asking for help!) is something like this 我现在正在做的事情(我确定是错误的,这就是为什么我要寻求帮助!)就是这样的事情

angular.module('test', [])
.factory('WatchModule', function(){
    return watchModule;
})

I run in to a problems: 我遇到一个问题:

This object (watchModule) is instantiated on DOM ready. 此对象(watchModule)在DOM就绪时实例化。 So, when angularJS first establishes this service, it returns undefined. 因此,当angularJS首次建立此服务时,它将返回undefined。 Perhaps as a direct result of this, angularJS does not continue to update after the object becomes defined. 也许直接的结果是,定义对象后,angularJS不会继续更新。

It's my hope that watching objects like this is possible. 我希望可以看到这样的对象。 The project I'm working on is a WebGL app, and it doesn't make too much sense for certain things to be "members" of angular. 我正在处理的项目是一个WebGL应用程序,对于某些东西成为angular的“成员”并没有太大的意义。 I'd simply rather watch them to retrieve some values. 我只想看他们检索一些值。

Angular can watch for objects that are attached to scope on either the root or some controller. Angular可以监视在根目录或某个控制器上附加到scope对象。 It can also watch on a function, by invoking it on digest cycles. 通过在摘要循环上调用功能,它也可以监视功能。

What it means in your case is that if you want to watch over watchModule you have to attach it to a scope or create a function that wraps it. 在您的情况下,这意味着如果您要监视watchModule ,则必须将其附加到作用域或创建一个包装它的函数。

$scope.watched=WatchModule;
   $scope.$watch('watched',function(newValue,oldValue) {
});

If this is not working then the case may be the reference that angular is watching is not the one that you are using. 如果这不起作用,则可能是角度正在观察的参考不是您正在使用的参考。 If you want to watch over sub properties of WatchModule, pass in an extra parameter to watch as true for object equality. 如果要监视WatchModule的子属性,请传入一个额外的参数以将其视为true以确保对象相等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM