我有一个 Web Worker,其工作是定期轮询 Web 服务以获取数据,然后将该数据插入 IndexedDB 数据库。
是否有任何推荐的方法来通知 AngularJS 模块对象存储的更新,因为所有更改都发生在 Angular 之外?
最佳答案
当你的网络 worker 完成时调用 $scope.$apply() 。您将需要获取引导 ng-app 的位置的“root”元素。例如:
HTML:
<div id="rootElement" ng-app="myApp">
...
</div>
JavaScript:
//Call $apply() to start an angular digest cycle where any updates you made to objects
//angular knows about will update the view.
angular.element(document.getElementById("rootElement")).scope().$apply();
编辑:包括示例 onmessage 订阅。
由于您的工作人员仅写入 IndexedDb,因此您还需要使用 postMessage 将该数据返回到您的 HTML(和 Angular )。例如,在您的 HTML 中:
var worker = new Worker("pathToWorker.js");
//Start worker in some way
worker.postMessage();
//Use data from the worker to update scope.
worker.addEventListener("message", function (e) {
//Get the data from the worker
var indexData = e.data;
//Update a scope variable (scopevar)
//Note: The element you query with angular.element must have the scope variable you
//are interested in.
angular.element(document.getElementById("MainController")).scope().$apply('scopevar=' + JSON.stringify(indexData));
}, false);
来自您的员工:
self.addEventListener("message", function (e) {
//Do work to write to IndexedDb
//PostMessage using the indexDb Data so angular can know about it.
self.postMessage({title: "Foo", data: "Bar"});
}
如果没有看到您的代码,我无法给出更具体的示例,但是来自工作人员的 postMessage 绝对是将数据从工作人员获取回 Angular 方法。
关于javascript - 从 AngularJS 外部触发更新/刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23895768/