Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing parent window angular scope from child window

I'm trying to update scope value on parent window from a child popup.But whenever I try to access the parent window scope,it returns undefined. As it involves two window, I couldn't create a fiddle for this. Code sample is pasted below.

Main page (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 window (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>

Here whenever I try to access scope from the angular element , as shown above in change method, it returns undefined [ae.scope()].But when the same code moved to a function in parent window [only difference in how 'ctrl' element is being accessed], it worked fine and I was able to update the scope variable. Can anyone point out what actually is going wrong here? Thanks

like image 630
Bibin Avatar asked Jun 09 '13 08:06

Bibin


1 Answers

Use the angular reference from the opener:

function change() {
  var s = window.opener.angular.element('#ctrl').scope();
  s.name="New Superhero";
  s.$apply();
}
like image 111
ejain Avatar answered Sep 25 '22 06:09

ejain