Reputation: 926
I'm creating a large AngularJs App, which requires User Login.
After authenticating user, a page is rendered to him and subsequent data is loaded later.
There are two ways for this:
XHR Fetch after Page Load:
This means sending an XHR request in 'run' block or somewhere to get LoggedIn user. say to '/api/current_user.json'
Data Embedded in HTML
To avoid initial load time of above method, I think its good to embed some JSON
in Html page as a <script>
tag.
However, I'm unable to get this data in 'script' tag from my module.run
block.
How can I do that ?
Upvotes: 2
Views: 3183
Reputation: 528
You can use the window object
or use ng-init
to pass the data from the rendered HTML to Angular:
Window Object
Assign your values to the "window" object. In Angular inject the $window service which references the window object and access your stored values.
Example:
In your HTML file:
<script>
window.init = { name: "John Doe" };
</script>
In the controller (should work similarly for the run block):
app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
$scope.user = $window.init;
...
}]);
Ng-Init
Create a function that initializes the values for you.
In the HTML:
<body ng-controller="MainCtrl" ng-init="initialize( { name: 'Jane Doe' } )">
In the controller:
$scope.initialize = function( json ) {
$scope.user2 = json;
};
Upvotes: 4