从AngularJS访问全局变量 [英] Access global variable from AngularJS
问题描述
我要初始化一个角模型JSON对象至极嵌入在HTML页面。例如:
I want to initialize a Angular model with a JSON object wich is embedded in a HTML page. Example:
<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:
function TagList($scope, $rootScope) {
$scope.tags = $rootScope.tags;
}
不过,这是行不通的。
But it doesn't work.
它的工作原理只有当我包括标记列表
直接插入HTML页面,并渲染JSON直接进入此功能。
It works only if I include the TagList
directly into the HTML page and render the json directly into this function.
我如何访问标记在一个单独的js文件
字段和角度控制?
How can I access the tags
field in a separate js file in a Angular controller?
推荐答案
有至少两种方式:
- 定义你的
标记
阵列在一个独立的脚本标签,在这种情况下,你的标记
变量将被绑定到窗口目的。注$窗口到控制器来访问你的窗口绑定变量。 - 声明你的
标记
的NG-INIT
指令内的数组。
- 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.
显示这两种解决方案:
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:
app.controller('AppController',
[
'$scope',
'$window',
function($scope, $window) {
$scope.tags = $window.tags;
}
]
);
我强烈反对污染的窗口对象。
I strongly advise against polluting window object.
这篇关于从AngularJS访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!