[英]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.