angular variable initialization

杀马特。学长 韩版系。学妹 提交于 2019-12-10 11:22:40

问题


I have a variable in angular controller, $scope.abc.

I have Sails as backend.

$scope.abc's initial value can be determined by backend when generating the page. After the page is displayed to user, $scope.abc may or may not be changed by the user.

I can have backend to generate a complete static page and let angular query the backend for initial value of $scope.abc. I feel it is not necessary as the initial value can be determined at the page's generation and should come as part of the page.

The question is: how to initialize $scope.abc when the webpage is being generated? Is there any way to provide data to angular js file, similar to res.view("",data)?


回答1:


You don't really have many options here. You can issue one more ajax request and load data. However it my be not ideal if during index page loading the data is already available. In this case you can inject it into additional script tag and access it from from there.

<script>
    // Make sure data is JSON encoded.
    window.appConfig = <%= data %>;
</script>
<script src="angular.js"></script>
<script src="app.js"></script>

And then I would set a constant service in the app to store data in it:

angular.module('app').constant('appConfig', {data: window.appConfig});

This way you could use it later in more Angular way, for example:

angular.module('app').controller(function($scope, appConfig) {
    $scope.config = appConfig.data.userId;
});

And if you are concerned with presence of the global variable appConfig, you can remove it in app run block, when constant is already set.



来源:https://stackoverflow.com/questions/27806416/angular-variable-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!