Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

javascript - AngularJS: open a new browser window, yet still retain scope and controller, and services

I'm writing an angularJS app. In this particular controller, I open a new browser window through the $window.open service. But in the new window, all the $scope variables are lost.

I tried to use window.parent but this doesn't work. In fact in the new browser window all the app services, controllers, or scopes are not in effect at all, is this true? Is there a way to open a new browser window yet still makes the new window belongs to the same angular app in the old window? I need to have access to some angularJS services and the scope of the controller that open that new window. Is this possible at all?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no [straightforward] way to make the new window belong to the same angular.js application, since the angular application is generally tied to the document, window, and events of the window where it was initialized either via an ng-app directive or by calling angular.bootstrap.

However, you can create a new angular module and application for your popup window. You could use the same basic services and controllers from your original application by including the appropriate javascript files.

Presuming your popup window needs data from the original application, you can pass that by using the window object returned from the window.open() method. For example, within your first angular application, open your popup window like so:

angular.module('originalModule').service('popupService', function(someOtherDataService) {

  var popupWindow = window.open('popupWindow.html');
  popupWindow.mySharedData = someOtherDataService.importantData;

});

Once your secondary "popup" angular application is initialized, it can then reference the shared data by reading window.mySharedData.

You can also create functions in each window that can be called from the other window. The popup window can call back into the original window by using the window.opener property. (window.parent refers to the parent window of frames, you want window.opener)

[Agreed, I'm sure that if you studied the angular source code you could find some clever way to use the same angular app for both windows. Such an attempt is beyond my ambition this evening.]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...