可以透過$window與ng-init directive二種方法,
最後回應的作者建議$window來存取全域的js變數
可參考此篇說明: http://stackoverflow.com/questions/15275160/access-global-variable-from-angularjs
以下是擷錄內容:
There are at least two ways:
Showing both solutions:
- Declare your tags array in a standalone script tags, in which case your tags variable will be bound to window object. Inject $window into your controller to access your window-bound variables.
- Declare your tags array inside the ng-init directive.
Showing both solutions:
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;
}
]
);
沒有留言:
張貼留言
留個話吧:)