10

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

主页 (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>

在这里,每当我尝试从角度元素访问范围时,如上面在更改方法中所示,它返回未定义的 [ae.scope()]。但是当相同的代码移动到父窗口中的函数时[仅在“ctrl”方式上有所不同元素正在被访问],它工作正常,我能够更新范围变量。谁能指出这里到底出了什么问题?谢谢

4

2 回答 2

10

I had a similar need and had the same problem accessing the scope using angular.element. I was was able to solve it as follows though:

In your main/parent controller do something like this:

$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');

Then in the child window controller you can access $windowScope like this:

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

An alternative to putting data directly into the scope would be to use $window scope to broadcast and/or emit events, which is the preferred way of cross-controller communication in angular.

于 2013-06-12T12:58:44.740 回答
10

使用angular开瓶器的参考:

function change() {
  var s = window.opener.angular.element('#ctrl').scope();
  s.name="New Superhero";
  s.$apply();
}
于 2013-11-06T20:18:56.953 回答