Sign up to get extra content & updates via email!

Thanks for signing up!
I appreciate it!

Adding Config to your AngularJS app

square
For the past few weeks, I’ve been building a Web App based on AngularJS.
I wanted it to act differently for different configurations, and I wanted to store the configuration in a simple Config file (sounds like standard procedure),
but for some odd reason, I couldn’t find any example or common way to do such a thing, so I improvised.

I simply wrote a new config.js file (where my app.js is, starting with Angular seed), and inside added a new config module.

config.js

var config_module = angular.module('myApp.config', [])
	.constant('APP_NAME','My App')
	.constant('APP_VERSION','0.1')
	.constant('FIRST_URL','http://www.google.com')
;

Then I added the newly created myApp.config module into my myApp.controllers module (inside controllers.js), as well as added the individual constants I want to have available inside each controller (sadly that was a must).

controllers.js

angular.module('myApp.controllers', ['myApp.config'])
  .controller('ListCtrl', ['$scope', '$http', 'APP_NAME', 'FIRST_URL', function($scope, $http, APP_NAME, FIRST_URL) {
  	$http.get(FIRST_URL).success(function(data) {
  		$scope.data = data;
  	});
  	$scope.APP_NAME = APP_NAME;
  }]);

At which point, if I want to, for instance get APP_NAME within the View,
I just add it to the scope in the controller:
controllers.js

angular.module('myApp.controllers', ['myApp.config'])
  .controller('ListCtrl', ['$scope', '$http', 'APP_NAME', 'FIRST_URL', function($scope, $http, APP_NAME, FIRST_URL) {
  	$http.get(FIRST_URL).success(function(data) {
  		$scope.data = data;
  	});
  	$scope.APP_NAME = APP_NAME;
  }]);

This seems to be an awful lot of trouble, I didn’t want to write .constant over and over again, so, I separated the data from the constant definition:
config.js

var config_data = {
  'APP_NAME': 'My App',
  'APP_VERSION': '0.1',
  'FIRST_URL': 'http://www.google.com'
}
angular.forEach(config_data,function(key,value) {
  config_module.constant(value,key);
}

This definitely makes it easier to change settings, plus it just looks better.
I still didn’t like the fact that I had to name all the variables I wanted from the config in advance,
so I simply packed them in an Object (Objects are defined with {}, and Arrays with []):
config.js

var config_data = {
  'GENERAL_CONFIG': {
    'APP_NAME': 'My App',
    'APP_VERSION': '0.1',
    'FIRST_URL': 'http://www.google.com'
  }
}
angular.forEach(config_data,function(key,value) {
  config_module.constant(value,key);
}

controllers.js

angular.module('myApp.controllers', ['myApp.config'])
  .controller('ListCtrl', ['$scope', '$http', 'GENERAL_CONFIG', function($scope, $http, GENERAL_CONFIG) {
  	$http.get(GENERAL_CONFIG.FIRST_URL).success(function(data) {
  		$scope.data = data;
  	});
  	$scope.APP_NAME = GENERAL_CONFIG.APP_NAME;
  }]);

That’s definitely more elegant, plus now I can divide my config into different sections and
only import the ones I need for each individual Controller.

I’d be happy to hear some other options to do this,
though I’m pretty satisfied with this solution.

Tagged with: , ,
Posted in Technology
8 comments on “Adding Config to your AngularJS app
  1. Eugene OZ says:

    You can just create service and declare all variable there.

  2. Ravindra Bharathi says:

    Hi,

    Thanks for the above snippet.

    I did exactly in the same way as instructed above, but I am getting the following error.

    Microsoft JScript runtime error: [$injector:modulerr] Failed to instantiate module myApp due to:
    [$injector:modulerr] Failed to instantiate module myApp.controllers due to:
    [$injector:nomod] Module ‘myApp.controllers’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

    Please let me know is there anything that I am missing.

    Thanks in advance.

  3. Ravindra Bharathi says:

    Only the 1st example works and if I change the config.js as per remaining examples it fails with the above error.

  4. airtonix says:

    Definitely a good start to a common problem, however grouping all your options together is something I would only do at the project level (probably not even then).

    For reusable, re-distributable angular modules I would go back to defining each config variable as a flat list of constants rather than trying to create a tree. re-distributable and reusable modules means treating the module as if it were a black box.

    Using a tree/hash/dictionary approach for a constant value means I have to redefine the entire tree/hash/dictionary if I just want to change FIRST_URL.

  5. Arno says:

    Hi all. I have just implemented this, but with a little tweak. I made an object of the config constant, so I can access all config vars without having to pass every variable to each controller. This way you can access all the config variables easily in as well your controller as your output templates.

    config.js

    var config_module = angular.module(‘app.config’, [])
    .constant(‘CONFIG’, {
    ‘SYSTEM_NAME’ : ‘My Angular JS project’,
    ‘GOOGLE_ANALYTICS_ID’ : ”,
    ‘BASE_URL’ : ”,
    ‘API_URL’ : ”,
    ‘SYSTEM_LANGUAGE’ : ”
    });

    controllers.js

    angular.module(‘app.controllers’, [‘app.config’])
    .controller(‘appController’, [‘$scope’, ‘CONFIG’, function($scope, CONFIG) {

    // Work with your CONFIG vars here

    // Pass the config vars to your scope
    $scope.config = CONFIG;

    }]);

    HTML

    This app is: {{config.SYSTEM_NAME}}

    • Asaf Zamir says:

      Hi, I appreciate your addition a lot.
      It’s been a while since I had a chance to fiddle with AngularJS, and I’m hoping to get back to it as soon as I can.

  6. Cisco says:

    angular.forEach(config_data,function(key,value) {
    config_module.constant(value,key);
    }

    I think it needs a ); at the end.

  7. Gleb says:

    We use the provider / config combination to inject server-side constants and configuration info into our angular application. See the blog post http://bahmutov.calepin.co/inject-valid-constants-into-angular.html

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Welcome to KidsIL
A blog for Web Development & Technology


Check out my new series about MeanJS: Take a look at StartCast.
A podcast with the sole purpose of interviewing co-founders of Startups in Europe & around the world.


You should try Berlin On Feier, an App I built for finding the best parties in Berlin.