javascript 从 AngularJS 访问全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15275160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access global variable from AngularJS
提问by deamon
I want to initialize a Angular model with a JSON object wich is embedded in a HTML page. Example:
我想用嵌入在 HTML 页面中的 JSON 对象初始化 Angular 模型。例子:
<html>
<body>
<script type="text/javascript" charset="utf-8">
var tags = [{"name": "some json"}];
</script>
<ul>
<li ng-repeat="tag in tags">{{tag.name}}</li>
</ul>
</body>
</html>
The tags
field cannot be resolved, because it is looked up in the $scope
. I tried to access the tags
field in my controller like this:
该tags
字段无法解析,因为它在$scope
. 我尝试tags
像这样访问控制器中的字段:
function TagList($scope, $rootScope) {
$scope.tags = $rootScope.tags;
}
But it doesn't work.
但它不起作用。
It works only if I include the TagList
directly into the HTML page and render the json directly into this function.
仅当我将TagList
直接包含在 HTML 页面中并将 json 直接呈现到此函数中时,它才有效。
How can I access the tags
field in a separate js file in a Angular controller?
如何tags
在 Angular 控制器中访问单独的 js 文件中的字段?
回答by Stewie
There are at least two ways:
至少有两种方式:
- Declare your
tags
array in a standalone script tags, in which case yourtags
variable will be bound to window object. Inject $window into your controller to access your window-bound variables. - Declare your
tags
array inside theng-init
directive.
tags
在独立脚本标签中声明您的数组,在这种情况下,您的tags
变量将绑定到 window 对象。将 $window 注入您的控制器以访问您的窗口绑定变量。tags
在ng-init
指令中声明您的数组。
Showing both solutions:
显示两种解决方案:
HTML:
HTML:
<body>
<script type="text/javascript" charset="utf-8">
var tags = [{"name": "some json"}];
</script>
<div ng-controller="AppController">
tags: {{tags | json}}
<ul>
<li ng-repeat="tag in tags">{{tag.name}}</li>
</ul>
</div>
<div>
<ul ng-init="tags = [{name: 'some json'}]">
<li ng-repeat="tag in tags">{{tag.name}}</li>
</ul>
</div>
</body>
JS:
JS:
app.controller('AppController',
[
'$scope',
'$window',
function($scope, $window) {
$scope.tags = $window.tags;
}
]
);
I strongly advise against polluting window object.
我强烈建议不要污染 window 对象。