从子窗口访问父窗口角度范围

Bib*_*bin 9 javascript angularjs angularjs-scope

我正在尝试从子弹出窗口更新父窗口的范围值.但是每当我尝试访问父窗口范围时,它都会返回undefined.因为它涉及两个窗口,我无法为此创建一个小提琴.代码示例粘贴在下面.

主页面(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>
Run Code Online (Sandbox Code Playgroud)

子窗口(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>
Run Code Online (Sandbox Code Playgroud)

这里每当我尝试从angular元素访问scope时,如上面的change方法所示,它返回undefined [ae.scope()].但是当相同的代码移动到父窗口中的函数时[只有'ctrl'的差异'正在访问元素],它工作正常,我能够更新范围变量.任何人都可以指出这里究竟出了什么问题吗?谢谢

use*_*331 10

我有类似的需求,并使用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');
Run Code Online (Sandbox Code Playgroud)

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

$scope.parentWindow = window.opener.$windowScope;
console.log($scope.parentWindow.food);
Run Code Online (Sandbox Code Playgroud)

将数据直接放入范围的替代方法是使用$ window范围来广播和/或发出事件,这是角度中跨控制器通信的首选方式.


eja*_*ain 10

使用angular开场白的参考:

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

  • 如果关闭调试信息https://docs.angularjs.org/api/ng/provider/$compileProvider#debugInfoEnabled,这将不再有效.由于建议禁用生产应用程序的调试,因此该解决方案不起作用. (4认同)