2

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 ?

1
  • 1
    .constant('user',myGlobalUser) take a look on how this topic is managed by mean.io folks Commented Mar 28, 2014 at 8:40

1 Answer 1

4

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;
};

plnkr

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @andrbmgi, but i prefer not to pollute global window object, is there some other way than this or this may be only one?
Point taken. You could always do delete $window.init; to unpolute ;). I updated the plnkr.
I included another option going with ng-init. This polutes your $scope with another function. A fix for that... you guessed delete $scope.initialize. The plnkr now contains both soultions side by side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.