[英]Access global variable from AngularJS
我想用嵌入在 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>
tags
字段无法解析,因为它是在$scope
查找的。 我尝试像这样访问控制器中的tags
字段:
function TagList($scope, $rootScope) {
$scope.tags = $rootScope.tags;
}
但它不起作用。
仅当我将TagList
直接包含在 HTML 页面中并将 JSON 直接呈现到此函数中时,它才有效。
如何访问 Angular 控制器中单独 js 文件中的tags
字段?
至少有两种方式:
tags
数组,在这种情况下, tags
变量将绑定到窗口对象。 将 $window 注入您的控制器以访问您的窗口绑定变量。ng-init
指令中声明你的tags
数组。显示两种解决方案:
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;
}
]
);
我强烈建议不要污染 window 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.