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

win*_*ler 51 global-variables angularjs

首先,我查了一下,但没有发现任何文章涉及我的问题.

如何在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,您需要访问全局变量.

有什么特别的方法吗?

Ada*_*mas 96

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

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>
Run Code Online (Sandbox Code Playgroud)

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;
}]);
Run Code Online (Sandbox Code Playgroud)

  • @ ogc-nick不,如果`$ window.variable1`改变`$ scope.variable1`将会过时. (5认同)
  • 这会监视$ window变量并在窗口变量发生变化时更新范围变量吗? (3认同)

Jul*_*lzt 12

将全局变量复制到控制器范围内的变量.

function MyCtrl($scope) {
   $scope.variable1 = variable1;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以像尝试一样访问它.但请注意,更改全局变量时,此变量不会更改.如果您需要,可以使用全局对象并"复制"它.由于它将通过引用"复制",它将是相同的对象,因此将应用更改(但请记住,在AngularJS之外执行操作将要求您执行$ scope.$ apply anway).

但是,如果您能描述一下您实际尝试实现的目标,那么也许是值得的.因为使用这样的全局变量几乎不是一个好主意,并且可能有更好的方法来达到预期的结果.