首先,我检查了,没有找到任何涉及我的问题的文章。
如何访问 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/