Set Global variable

23 views
Skip to first unread message

Bjarni

unread,
Jul 23, 2017, 12:13:55 PM7/23/17
to Angular and AngularJS discussion

Hi, I'm trying to use a global variable to pass a value to a referred service/application.

From my index.html file:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My Web</title>
<script type="text/javascript" src="http://XXX_Host.com/XXX.js"></script>
<script>
var GlobalVariable =
"DefaultValue";
</script>
</head>
<body ng-app="MyApp" >
<div class="ngview" ng-view=""></div>
<script src="./dist/app.min.js"></script>
</body>
</html>


From my angular module I fire a CustomEvent which tells XXX to read window.GlobalVariable and display it's value.  Before I fire this event I put GlobalVariable to a proper value but the XXX only "sees" and displays the initial default value. 

Is there a way to do this this way ?

I've tried to use window.GlobalVariabæ3 = ""New value" as well as the Angular service stuff.

Kind regards,
Bjarni

Sander Elias

unread,
Jul 23, 2017, 11:31:58 PM7/23/17
to Angular and AngularJS discussion
Hi Bjarni,

This is more a typescript issue as it is an angular one. 
try this in the code you want to use your global:

declare var GlobalVariable:string; // try to avoid any, but if you have to, you can use any.

Regards
Sander

Bjarni

unread,
Jul 24, 2017, 1:55:55 PM7/24/17
to Angular and AngularJS discussion
Thanks Sander, but I don't quite understand.   Are you suggesting I should be using typescript in my project and by doing so I could update this global variable from my angular controller ?

Regards, Bjarni

Sander Elias

unread,
Jul 24, 2017, 10:17:58 PM7/24/17
to Angular and AngularJS discussion
Hi Bjarni,

No, sorry, I had seen this request so many times for Angular version 2 and up, that I assumed you where there.
In AngularJS you can just use the variable. However, keep in mind that when you are using a primitive (in this case a string) values are copied over, not passed by reference. Changing the value of a primitive will not magically update old copies. 

Regards
Sander
Reply all
Reply to author
Forward
0 new messages