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.

1
  • 2
    The problem is alert(window.globalVar); get's run before $window.globalVar="test"; Commented Jun 6, 2017 at 14:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Which function did you set the Timeout to?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.