[英]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 .通过从此答案中学习如何访问 angularjs 指令中的全局 js 变量,我能够使用$window
服务成功访问 AngularJs 控制器中的 javascript 变量。
Here is a code pen to demonstrate what I mean: https://codepen.io/anon/pen/lznxe这是一个代码笔来演示我的意思: https : //codepen.io/anon/pen/lznxe
I want to achieve the opposite, that is accessing $window.variable
in my template javascript.我想实现相反的目标,即在我的模板 javascript 中访问$window.variable
。
I tried doing this.我试过这样做。 However, the alert box only shows the output:但是,警报框仅显示输出:
Undefined不明确的
Template Javascript:模板Javascript:
<script>
alert(window.globalVar);
</script>
AngularJS Controller: AngularJS 控制器:
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这是一个代码笔来演示我所描述的问题: 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 .主要目标是访问要在模板 Javascript 中使用的$scope
变量。 Thanks in advance.提前致谢。
It looks like the script in the <script>
tags get executed too early.看起来<script>
标签中的<script>
执行得太早了。 With a setTimeout
of 1000
it seems to work. setTimeout
为1000
它似乎可以工作。 Try to add an onLoad
on your <body>
tag, so your script gets executed after the variable is defined.尝试在<body>
标签上添加一个onLoad
,以便在定义变量后执行脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.