Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Approach for Configuration File for an Angular/RequireJS Application?

Is there a commonly accepted best practice for maintaining a configuration file that is available on the client side (sort of an equivalent of the AppSettings section on the server side in an ASP.NET application)?

Our application is based on Angular. Our desire is to externalize environment-specific settings (like remote system URLs, etc) from the code itself, so that ideally an Ops person and not a developer can modify settings in one place.

Thanks in advance for any insight!

like image 503
blaster Avatar asked May 02 '13 18:05

blaster


1 Answers

I don't think it's a good idea to use a config.js file when developing AngularJS apps. The reason being, you will break any possibility for automatic testing.

Instead, I create a "Settings" service in which I specify my app specific context. For example:

angular.module('settings',[]).factory('SettingsService',function(){

   var service={};

   // Insert your settings here
   service.ServerPath = 'whateverwhatever';
   service.ImagePath  = 'bla bla bal';

   return service;

});

Then inject the SettingsService into controllers that need access to the settings.

Ofcourse, (which I omitted for simplicity here), you could instead create the ServiceService with an empty body, and then in the application .run() method fetch the settings from the server.

I use the simple described way, and maintain a SettingsService for each deployment type ("development", "test", "production" etc). Then just include the right SettingsService in your build-script depending on the target (I use Grunt, but you could use Ant also).

like image 108
Spock Avatar answered Sep 28 '22 01:09

Spock