Vikas Raturi
Vikas Raturi

Reputation: 926

How to add initial data to angularjs app from rendered html

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:

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

Answers (1)

andrbmgi
andrbmgi

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

plnkr

Upvotes: 4

Related Questions