angularjs - 如何在 AngularJS 指令中访问全局 js 变量

标签 angularjs global-variables

首先,我检查了,没有找到任何涉及我的问题的文章。

如何访问 angularJS 内置指令中预定义的 js 全局变量?

例如我在 <script>var variable1 = true; </script> 中定义了这个变量

然后我编写一个 AngularJS 指令:

<div ng-if="variable1">Show some hidden stuff!</div>

这实际上不起作用。

然后我被告知我应该使用 ng-init

所以我在其他地方编写了代码,例如:

<div ng-init = "angularVariable1 = variable1"></div>

这显然不起作用......这就像一个恶性循环。需要访问预定义的js全局变量,那么就需要使用ng-init;为了使用 ng-init,您需要访问全局变量。

有什么特殊的方法可以做到这一点吗?

最佳答案

我创建了一个working CodePen example演示如何在 AngularJS 中以正确的方式执行此操作。 Angular $window service应该用于访问任何全局对象,因为直接访问 window 会使测试变得更加困难。

HTML:

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

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;
}]);

关于angularjs - 如何在 AngularJS 指令中访问全局 js 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19383725/

相关文章:

javascript - Angular JS - 数字过滤器 - 负数时更改颜色

angularjs - 使用 Angular 数据表时如何创建 Jasmine 单元测试

python - 将局部变量转换为全局变量

c++ - 如何引用与 C++ 中的局部变量同名的全局变量?

javascript - 是否可以将全局变量与 $(this) 一起使用?

c++ - 如何避免在 C++ 中意外地重新声明全局常量?

python - 如何使在函数内创建的变量成为全局变量?

javascript - angularjs拦截器:why is it not receiving the proper status code and message in $http interceptor

angularjs - 在包装 div 内部时,Angular ng-click 在 IE 11 上不起作用

javascript - AngularJS 通过 for 循环进行 HTTP post 调用