0

I have 3 json files to build the front-end of my web app:

  1. config.json to get all options based on the user rights
  2. preferences.json which is the user preferences
  3. foo.json which is the object that the user will modify thanks the web app

In my main controller, config or Run (I don't know what is the best way), I would like to load all this json and store them in the $rootScope to build all instances of my components in the HTML page.

I already tried to do this...

$http.get('config/config.json').success(function(configResponse) {
  $rootScope.config = configResponse;
});
$http.get('preferences/preferences.json').success(function(prefResponse) {
  $rootScope.preferences = configResponse;
});
$http.get('foo/foo.json').success(function(fooResponse) {
   $rootScope.foo = fooResponse;
});
console.dir($rootScope);

Unfortunately, that does not work. Someone has an idea and the best way to do it in Angular 1.5 which will facilitate the transition in Angular 2.0 ?

J.BizMai
  • 2,621
  • 3
  • 25
  • 49
  • 1
    Define "does not work", precisely. Where and how are you executing these lines. What happens precisely? You realize that the line `console.dir(...)`is executed much before the three values are stored in the scope, right? the first A in AJAX means "asynchronous". – JB Nizet Apr 29 '16 at 20:37

1 Answers1

0

Don't use $rootScope, for application configuration is recommended use a specific module with the configuration info and register each configuration block as `constant'.

In your case the server side configuration made a bit more complex. See Asynchronously Bootstrapping AngularJS Applications with Server-Side Data

(function() {
    var appConfig=angular.module("app.config");
    var initInjector = angular.injector(["ng"]);
    var $http = initInjector.get("$http");

    $http.get('config/config.json').success(function(configResponse) {
       appConfig.constant("config", configResponse);
    });
   $http.get('preferences/preferences.json').success(function(prefsResponse {
       appConfig.constant("preferences", preferencesResponse);
    });


})());

At your app module include the app.config and then you can inject the config,preferences or foo to your angular controllers, services,...

angular.module("app",["app.config"])
pdorgambide
  • 1,787
  • 19
  • 33
  • Thanks a lot. That works !!! just 'var appConfig=angular.module("app.config");' --> ' var appConfig=angular.module("app.config" [ ]);' , 'prefsResponse ' --> 'preferencesResponse' and to use config, preferences or foo in controllers, we need to add as parameters `angular.module('GenThemeApp').controller('appController', ['config', function (config){ ....` – J.BizMai May 02 '16 at 15:09
  • Glad to be helpful!, If really works please mark as solved. – pdorgambide May 03 '16 at 13:41