如何在角度应用程序启动之前从.json文件加载一些设置

hap*_*400 11 json angularjs

我正在构建使用CORS请求的应用程序.我使用的每个请求都从常量中获取主机地址

angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})
Run Code Online (Sandbox Code Playgroud)

在每个服务我用来发送这样的请求:

angular.module('siteApp').factory('DocsSvc', function ($http, baseUrl) {
   var baseurl = baseUrl.server ;
   $http.get(baseurl + 'document')
Run Code Online (Sandbox Code Playgroud)

是否有可能使'htttp:// localhost /'值 - 来自config.json文件到baseUrl constant或baseUrl factory?我的意思是:我如何从ajax请求中加载一些东西,让它可以访问app模块

我试过了:

.run(['$rootScope', , function ($rootScope) {

  $.ajax('config.json', {async: false})
  .success(function (data) {
    $rootScope.HOST = data.HOST;
  });
Run Code Online (Sandbox Code Playgroud)

并尝试从baseUrl访问它:

angular.module('siteApp').factory('baseUrl',function($rootScope) {
 return {
  server: $rootScope.HOST
Run Code Online (Sandbox Code Playgroud)

但没有运气 - baseUrl.server未定义为函数

vin*_*esh 7

你可以使用run角度的方法.

  var app = angular.module('plunker', []);

  app.run(function($http, $rootScope){
  $http.get('config.json')
  .success(function(data, status, headers, config) {
    $rootScope.config = data;
    $rootScope.$broadcast('config-loaded');
  })
  .error(function(data, status, headers, config) {
    // log error
    alert('error');
  });
})

app.controller('MainCtrl', function($scope, $rootScope) {
  $scope.$on('config-loaded', function(){
    $scope.name = $rootScope.config.name;  
  });
});
Run Code Online (Sandbox Code Playgroud)

看到这个plunker