[英]Access global variable from AngularJS
I want to initialize a Angular model with a JSON object which is embedded in a HTML page.我想用嵌入在 HTML 页面中的 JSON 对象初始化 Angular 模型。 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
. tags
字段无法解析,因为它是在$scope
查找的。 I tried to access the tags
field in my controller like this:我尝试像这样访问控制器中的
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?如何访问 Angular 控制器中单独 js 文件中的
tags
字段?
There are at least two ways:至少有两种方式:
tags
array in a standalone script tags, in which case your tags
variable will be bound to window object.tags
数组,在这种情况下, tags
变量将绑定到窗口对象。 Inject $window into your controller to access your window-bound variables.tags
array inside the ng-init
directive.ng-init
指令中声明你的tags
数组。 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 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.