Ivan Alek Ivan Alek - 8 months ago 162
AngularJS Question

Configuration file in AngularJS

What is the best way to create config file (Something like web config in .net), for storing urls, and other constants that may vary during the application deploy?


Use the .constant() method:

angular.module('app').constant('MONGOLAB_CONFIG', {
  baseUrl: '/databases/',
  dbName: 'ascrum'

like in this example.

Then you can just inject it where you need the constants.

You can have different files defining different constants for development or production, and then use a tool like Grunt to use this or that file according to the environment.

Let's assume you have this kind of folder structure:

|  |-app.js
|  |-anotherfile.js
|  |-...
|  |-dev.js
|  |-prod.js

dev.js and prod.js defines the same .constant() service with different values. Then you can get the proper file to be concatenated with a gruntFile like that:

grunt.registerTask('default', ['concat']);

  env : process.env.NODE_ENV,
  src: {
    javascript: ['js/*.js'],
    config: ['env/<%= env %>.js']
  concat: {
    javascript: {
      src:['<%= src.config %>', '<%= src.javascript %>'],

By running grunt you would get a myapp.js file containing the good constants.

Edit: with Gulp you can do it like this:

var paths = [
  'env/' + process.env.NODE_ENV + '.js',

var stream = gulp.src(paths)