我已经能够想出一种跨多个窗口共享服务的方法,但它仍然有点笨拙,如果可用,我希望有更好的解决方案。
在您作为 chrome 应用程序的父窗口中,您将使用以下代码启动一个新窗口。
chrome.app.window.create("view2.html", options, function(window){
//This function is a callback that is called when the child
//window has been created and launched.
//I believe it has first access to the window object before any child code
//Note that the parameter is not the true javascript window but only
//a chrome wrapper object. The window is window.contentWindow
//We are going to place an object on the window that the child code will look for
window.contentWindow.sharedDependencies = {
shared_dependency: dependency,
other_shared_dep: dependency2
}
});
然后当您的第二个页面加载时,它可以检查窗口上的属性sharedDependencies 并适当地加载它们。
//The main module must have the dependency module
angular.module("main_app", ["dependancyModule"]);
var deps = angular.module("dependancyModule", []);
if(typeof window.sharedDependencies === "object")
{
for(var name in sharedDependencies)
//Register each dependency as a value because we are receiving
//it as a value- not as a factory method or a service method.
deps.value(name, sharedDependencies[name]);
}
我在一个打包的应用程序中尝试了这个,它工作了,但是你必须手动调用 $apply(),因为在一个上下文中更改某些内容不会提醒另一个上下文。我还没有想到一个优雅的解决方案。
我也是 Angular 的初学者,所以这可能不支持 Angular 的其他方面。除了与共享对象的简单绑定之外,我还没有对其进行测试。