如何进入全球JS变量AngularJS指令 [英] How to access global js variable in AngularJS directive

查看:104
本文介绍了如何进入全球JS变量AngularJS指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我检查,我没有找到任何物品覆盖我的问题。

First of all, I checked and I didn't find any article covering my question.

如何angularJS内置指令访问pre-JS定义的全局变量?

How to access a pre-defined js global variable in angularJS built-in directive?

例如,我定义这个变量<脚本> VAR变量1 = TRUE; < / SCRIPT>

For example, I define this variable in <script>var variable1 = true; </script>

然后我写了AngularJS指令:

Then I write a AngularJS directive:

&LT; D​​IV NG-IF =变量1&gt;显示一些隐藏的东西&LT;!/ DIV&GT;

这并没有真正发挥作用。

This does not really work.

然后我了解到,我应该使用 NG-INIT

Then I'm informed that I should use ng-init

所以我写了code别的地方,如:

So I wrote code somewhere else like:

&LT; D​​IV NG-的init =angularVariable1 =变量1&GT;&LT; / DIV&GT;

这显然不工作,以及...这就像一个恶性循环。您需要访问pre-JS定义的全局变量,那么你需要使用NG-初始化;为了使用NG-初始化,您需要访问全局变量。

And this apparently does not work as well...this is like a vicious cycle. You need to access pre-defined js global variables, then you need to use ng-init; in order to use ng-init, you need to access global variables.

要做到这一点有什么特别的方法吗?

Any particular way to do this?

推荐答案

我创建了一个工作codePEN例如演示如何做这正确的方式AngularJS。 应该被用来访问任何全局对象,因为该角 $窗口服务直接访问窗口使测试变得更加困难。

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript的:

JavaScript:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);

这篇关于如何进入全球JS变量AngularJS指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆