从子窗口访问父窗口的角度作用域

Accessing parent window angular scope from child window

本文关键字:窗口 作用域 访问      更新时间:2023-09-26

我试图从子弹出窗口更新父窗口的作用域值。但是每当我尝试访问父窗口作用域时,它返回未定义。因为它涉及两个窗口,所以我不能为它创建一个小提琴。代码示例粘贴在下面。

主页(Main .html)

<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script>
     var myApp = angular.module('myApp',[]);
     function MyCtrl($scope) {
        $scope.name = 'Superhero';
    }
    </script>
  </head>
  <body ng-app="myApp">
   <div id="ctrl" ng-controller="MyCtrl">
      Hello, {{name}}!
      <input type="button" value="Open popup!!" onclick="window.open('child.html');"/>
    </div>
  </body>
</html>

子窗口(Child .html)

<!doctype html>
<html >
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script>
     function change(){
      var e = window.opener.document.getElementById('ctrl');
      var ae = angular.element(e);
      var s = ae.scope();
      s.name="New Superhero";
      s.$apply();
     }
    </script>
  </head>
  <body>
      <input type="button" value="Update parent scope!" onclick="change();"/>
  </body>
</html>

这里,每当我尝试从angular元素访问作用域时,就像上面的change方法一样,它返回undefined [ae.scope()]。但是,当相同的代码移动到父窗口中的函数时(只是"ctrl"元素被访问的方式不同),它工作得很好,我能够更新范围变量。有人能指出到底哪里出了问题吗?由于

使用开瓶器中的angular引用:

function change() {
  var s = window.opener.angular.element('#ctrl').scope();
  s.name="New Superhero";
  s.$apply();
}

我也有类似的需求,并且在使用angular.element访问作用域时遇到了同样的问题。我能够解决它,尽管如下:

在你的主/父控制器中这样做:

$scope.food = 'Mac & Cheese';
window.$windowScope = $scope;
$window.open('views/anotherWindow.html', '_blank','menubar=yes,toolbar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes,personalbar=yes');

然后在子窗口控制器中,你可以像这样访问$windowScope:

$scope.parentWindow = window.opener.$windowScope;
console.log($scope.parentWindow.food);

将数据直接放入作用域的另一种选择是使用$window scope来广播和/或发出事件,这是angular中跨控制器通信的首选方式。