March 2, 2014 . . Comments

Using Environment configuration with Yeoman Angular Generator

I am using generator-angular and needed to inject environment variables. As it turns out it was really simple using grunt-ng-constant
To install ng-constant
npm install grunt-ng-constant --save-dev
We need to then add ngconstant to our Grunfile in the init section
// Define the configuration for all the tasks

    ngconstant: {
      options: {
        space: '  '
      // Environment targets
      development: [{
        dest: '.tmp/scripts/config.js',
        wrap: '"use strict";\n\n <%= __ngModule %>',
        name: 'config',
        constants: {
          ENV: {
            name: 'development',
            foo: 'We are in development!'
      production: [{
        dest: '.tmp/scripts/config.js',
        wrap: '"use strict";\n\n <%= __ngModule %>',
        name: 'config',
        constants: {
          ENV: {
            name: 'production',
            foo: 'We are in production!'
Make sure that you have the destination in production and development set to .tmp. I was facing problems that the config files where not generated properly.
For development look for this section and add the ngconstant:development[
      'ngconstant:development',//add this
And for build add ngconstant:production
  grunt.registerTask('build', [
    'ngconstant:production',//add this
In our index html we need to include the config file
<!--build:js({.tmp,app}) scripts/scripts.js -->
<script src="/scripts/app.js"></script>
<script src="/scripts/config.js"></script>
<!-- endbuild -->
If you now run grunt serve or grunt build this will generate following module
"use strict";

 angular.module("config", [])

.constant("ENV", "production")

.constant("apiEndpoint", "")

Inject the module into your app
angular.module('myApp', [
Now whenever you require you can inject ENV as a dependency and use
  .controller('Ctrl', function (ENV) {
Happy coding!


Please feel free to leave any comments as long as they're related to the topic.