如何初始数据呈现的HTML添加到angularjs应用 [英] How to add initial data to angularjs app from rendered html
问题描述
我创建一个大AngularJs应用程序,这需要用户登录。结果
之后的认证的用户,页面呈现给他,随后的数据以后加载。
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.
有两种方法是:
-
页面加载后XHR取:结果
这意味着在发送跑块中的XHR请求或某处获得的的loggedIn 的用户。说/ API / current_user.json
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'
数据在HTML 结果嵌入
为了避免上述方法的初始加载的时候,我觉得它很好的嵌入一些 JSON
在HTML页面作为<脚本>
标记。
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.
不过,我无法得到从我的 module.run
块的'script'标签这个数据。结果
我该怎么做?
However, I'm unable to get this data in 'script' tag from my module.run
block.
How can I do that ?
推荐答案
您可以使用窗口对象
或使用 NG-INIT
从呈现的HTML角度来传递数据:
You can use the window object
or use ng-init
to pass the data from the rendered HTML to Angular:
窗口对象
您的分配值窗口对象。在角注入它引用窗口对象上的$窗口服务和访问存储的值。
Assign your values to the "window" object. In Angular inject the $window service which references the window object and access your stored values.
例如:
在你的HTML文件:
<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;
...
}]);
吴-INIT
创建为你初始化值的函数。
Create a function that initializes the values for you.
在HTML:
<body ng-controller="MainCtrl" ng-init="initialize( { name: 'Jane Doe' } )">
在控制器:
$scope.initialize = function( json ) {
$scope.user2 = json;
};
这篇关于如何初始数据呈现的HTML添加到angularjs应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!