简体   繁体   中英

How to access AngularJS scope variable from template script using $window

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM