Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is possible to load some setting from .json file before angular app starts

Tags:

json

angularjs

i'm building application which uses CORS requests. Each request i use get host address from a constant

angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})

And in each service i use to send request like this:

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

Is it possible to make 'htttp://localhost/' value - to came from config.json file into baseUrl constant or baseUrl factory? I mean : how can i load something from ajax request an make it accessible to app modules

i have tried:

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

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

And tried to access it from baseUrl:

angular.module('siteApp').factory('baseUrl',function($rootScope) {
 return {
  server: $rootScope.HOST

But no luck - the baseUrl.server comes undefined into functions

like image 819
happyZZR1400 Avatar asked Dec 31 '14 11:12

happyZZR1400


2 Answers

You can use run method of angular.

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

see this plunker

like image 154
vinesh Avatar answered Sep 20 '22 20:09

vinesh


If you want to do it even before the angular app starts, you can, instead of using the ng-app directive, use the bootstrap function.

From: https://docs.angularjs.org/api/ng/function/angular.bootstrap

<!doctype html>
<html>
<body>
<div ng-controller="WelcomeController">
  {{greeting}}
</div>

<script src="angular.js"></script>
<script>
  var app = angular.module('demo', [])
  .controller('WelcomeController', function($scope) {
      $scope.greeting = 'Welcome!';
  });
  // Do your loading of JSON here
  angular.bootstrap(document, ['demo']);
</script>
</body>
</html>
like image 45
Lars Anundskås Avatar answered Sep 19 '22 20:09

Lars Anundskås