I want to initialize a Angular model with a JSON object which 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.
It works only if I include the TagList
directly into the HTML page and render the JSON directly into this function.
How can I access the tags
field in a separate js file in a Angular controller?
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. Inject $window into your controller to access your window-bound variables.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;
}
]
);
Plnkr
I strongly advise against polluting window object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With