AngularJS在应用程序启动时加载configuration

我需要在我的AngularJS应用程序启动时加载一个configuration文件(JSON格式),以便加载将在所有api调用中使用的参数。 所以我想知道是否有可能在AngularJS中这样做,如果是的话,我将在哪里/何时加载configuration文件?

注意: – 我需要将configuration文件参数保存在一个服务中,所以我需要在加载任何控制器之前加载json文件内容,但服务单元可用 – 在我的情况下,使用外部json文件是必须的应用程序客户端需要能够轻松地从外部文件更新应用程序configuration,而不需要通过应用程序源。

EDITED

这听起来像你试图做的是configuration一个服务的参数。 为了asynchronous加载外部configuration文件,您必须在数据加载完成callback中自行引导angular度应用程序,而不是使用自动增强打包。

考虑这个例子的服务定义实际上并没有定义服务的URL(这可能类似于contact-service.js ):

 angular.module('myApp').provider('contactsService', function () { var options = { svcUrl: null, apiKey: null, }; this.config = function (opt) { angular.extend(options, opt); }; this.$get = ['$http', function ($http) { if(!options.svcUrl || !options.apiKey) { throw new Error('Service URL and API Key must be configured.'); } function onContactsLoadComplete(data) { svc.contacts = data.contacts; svc.isAdmin = data.isAdmin || false; } var svc = { isAdmin: false, contacts: null, loadData: function () { return $http.get(options.svcUrl).success(onContactsLoadComplete); } }; return svc; }]; }); 

然后,在准备好的文档上,您将调用加载您的configuration文件(在这种情况下,使用jQuery)。 在callback中,您将使用加载的json数据来执行angular度应用.config。 运行.config后,您将手动引导应用程序。 非常重要:如果你正在使用这个方法,那么不要使用ng-app指令,否则angular会引导自己。查看这个URL获得更多的细节:

http://docs.angularjs.org/guide/bootstrap

像这样:

 angular.element(document).ready(function () { $.get('/js/config/myconfig.json', function (data) { angular.module('myApp').config(['contactsServiceProvider', function (contactsServiceProvider) { contactsServiceProvider.config({ svcUrl: data.svcUrl, apiKey: data.apiKey }); }]); angular.bootstrap(document, ['myApp']); }); }); 

更新:这是一个JSFiddle示例: http : //jsfiddle.net/e8tEX/

我无法得到方法build议我的基思·莫里斯工作。

所以我创build了一个config.js文件,并将其包含在index.html之前的所有angular度文件中

config.js

 var configData = { url:"http://api.mydomain-staging.com", foo:"bar" } 

的index.html

 ... <script type="text/javascript" src="config.js"></script> <!-- compiled JavaScript --><% scripts.forEach( function ( file ) { %> <script type="text/javascript" src="<%= file %>"></script><% }); %> 

然后在我的运行function,我把configurationvariables设置为$ rootScope

 .run( function run($rootScope) { $rootScope.url = configData.url; $rootScope.foo = configData.foo; ... }) 

你可以像这样使用常量:

 angular.module('myApp', []) // constants work //.constant('API_BASE', 'http://localhost:3000/') .constant('API_BASE', 'http://myapp.production.com/') //or you can use services .service('urls',function(productName){ this.apiUrl = API_BASE;}) //Controller calling .controller('MainController',function($scope,urls, API_BASE) { $scope.api_base = urls.apiUrl; // or API_BASE }); 

//在html页面中调用{{api_base}}

还有其他几个选项,包括.value.config但都有其局限性。 .config是很好的,如果你需要到达服务的提供者做一些初始configuration。 .value类似于常量,除了可以使用不同types的值。

https://stackoverflow.com/a/13015756/580487