1

I am able to successfully access the javascript variable in my AngularJs controller using the $window service, by learning from this answer how to access global js variables in angularjs directive.

Here is a code pen to demonstrate what I mean: https://codepen.io/anon/pen/lznxe

I want to achieve the opposite, that is accessing $window.variable in my template javascript.

I tried doing this. However, the alert box only shows the output:

Undefined

Template Javascript:

<script>
   alert(window.globalVar);
</script>

AngularJS Controller:

 app.controller("myCtrl", function($scope,$http,$interval,$window){
     $window.globalVar="test";
 )};

Here is a code pen to demonstrate the problem that I am describing: https://codepen.io/anon/pen/NgqNBa

How can I achieve what I want? The main goal is to access the $scope variable to be used in the Template Javascript. Thanks in advance.

Community
  • 1
  • 1
Ernest Soo
  • 194
  • 3
  • 17

1 Answers1

1

It looks like the script in the <script> tags get executed too early. With a setTimeout of 1000 it seems to work. Try to add an onLoad on your <body> tag, so your script gets executed after the variable is defined.

Jeff Huijsmans
  • 1,388
  • 1
  • 14
  • 35
  • Which function did you set the Timeout to? – Ernest Soo Jun 06 '17 at 14:35
  • I waited 1000ms before triggering `alert(window.globalVar);`. But don't rely on the timeout, that's bad practice; I only used it to confirm what @George said in the comment on your question. – Jeff Huijsmans Jun 06 '17 at 14:44