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
Use the angular
reference from the opener:
function change() {
var s = window.opener.angular.element('#ctrl').scope();
s.name="New Superhero";
s.$apply();
}
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.