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

后端 未结 3 621
耶瑟儿~
耶瑟儿~ 2020-11-29 00:12

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

3条回答
  •  無奈伤痛
    2020-11-29 00:52

    A window which is opened by your main window will architecturally be unable to share the same root scope with its parent. Because the angular scope is defined per DOM element. You need to bootstrap a completely new AngularJs app in the child window.

    Provided a new window (child), which hosts another AngularJs application, has been spawned by the main window (parent), a following solution may be viable: referencing the root scope of the newly spawned window from the parent window and then communicating an event through the scope of the child window from the parent. Something like this:

    On the child window:

    $rootScope.$on("INTER_WINDOW_DATA_TRANSFER", function (data, args) {                   
                console.log("DATA RECEIVED: " + args.someData);
            });
    

    From the parent window you take hold of the DOM element (in the child window) on which the ng-app attribute is defined (it's root scope) (pseudocode):

    var newWindowRef = $window.open("", "New Window", "width=1280,height=890,resizable=1");
    var newWindowRootScope = newWindowRef.angular.element("#MY_ROOT_APP_ELEMENT_ID").scope();
    newWindowRootScope.$broadcast("INTER_WINDOW_DATA_TRANSFER", {someData : "I'm data"});
    

提交回复
热议问题