Rodrigo Rodrigo - 2 months ago 7
AngularJS Question

Global variables are undefined in new pop up window, while they were defined beforehand

I tried to create two buttons, so that when I click on each- I will get a pop up small window, with a content that it will get while onloading.

This is the code:

index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp">
<p ng-controller="ctrl">
<span ng-repeat="x in items">
<button ng-click="parentFunc(x.fieldOne,x.fieldTwo)">{{x.fieldOne}}</button>
<br><br>
</span>
</p>
<script>items();</script>
</body>
</html>


script.js:

var title, content;

function items(){
angular.module('myApp', []).controller('ctrl', function($scope) {
$scope.items = [
{fieldOne:"field1", fieldTwo:"field1 content"},
{fieldOne:"field2", fieldTwo:"field2 content"}
];
$scope.parentFunc=function(titleTmp,contentTmp){
title=titleTmp;
content=contentTmp;
var OpenWindow = window.open('popUp.html','_blank','width=500, height=400');
return false;
}
});
}

function codeAddress() {
document.getElementById("title").innerHTML=title;
document.getElementById("content").innerHTML=content;
}


popUp.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="codeAddress();">
<h1 id="title"></h1>
<div id="content"></div>
</body>
</html>


The new pop up window open as expected, but the
h1
and
div
in it get
undefined
. I tried to debug it, and I saw that after the first two lines of
parentFunc
are executed, the global variables
title
and
content
get what I expect and they are not undefined. However, when the third line is executed and the new window get opened- the global variables are undefined.

Why the two global variables are undefined in the pop up window?

And how can I solve this?

Answer

Your method won't work : you are trying to reload the script.jsand then, the vars are reinitialized.

Add your vars in the URL :

var OpenWindow = window.open('popUp.html?title='+titleTmp+'&content='+contentTmp,'_blank','width=500, height=400');

Then, in your second page, read those parameters :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script type="text/javascript">
    function codeAddress(){
     var title  = GET_TITLE_FROM_PARAMETER;
     var content = GET_CONTENT_FROM_PARAMETER;
     document.getElementById("title").innerHTML=title;
     document.getElementById("content").innerHTML=content;
    }
    </script>
</head>
<body onload="codeAddress();">
<h1 id="title"></h1>
<div id="content"></div>
</body>
</html>    

And of course, remove codeAddress from the first page as it's useless.

FYI, to get the parameters values, please check this answer.