1

I want to do something like

gulp build --param1=abc

and I want this param to be available in Angular Service/Controller. Is there a way I can do that?

ap_snitch
  • 367
  • 4
  • 11
  • what do u mean in ur angular service/controller? – yangli1990 Feb 05 '15 at 21:37
  • @YangLi I want to be able to use the value 'abc' in an AngularJS service. for now I have piped the value in file and importing that file with $http in my service. I am not sure if there is a better approach. – ap_snitch Feb 05 '15 at 21:44
  • Possible duplicate of [Is it possible to pass a flag to Gulp to have it run tasks in different ways?](http://stackoverflow.com/questions/23023650/is-it-possible-to-pass-a-flag-to-gulp-to-have-it-run-tasks-in-different-ways) – Louis Dec 14 '15 at 17:05

1 Answers1

5

Yes. I would recommend in your Gulp config, you create an Angular constant that can be injected into any part of the application.

var ngConstant = require('gulp-ng-constant');
var args = require('yargs').argv;

gulp.task('constant', function () {
  var selectedConstant = args.env || 'dev'; // if --env is not declared, assume dev
  var constants = {
    dev: {
      ENV: {
        'api': 'api.someUrl.com',
        'url': 'dev.url.com'
      }
    },
    prod: {
      ENV: {
        'api': 'api.someUrl.com',
        'url': 'dev.url.com'
      }
    },
  };

  return ngConstant({
      name: 'app', // name of your module
      constants: constants[selectedConstant],
      stream: true
    })
    .pipe(gulp.dest('src'));
});

gulp.task('build', function () {
  runSequence(
    ['constant']
  )
});

Now, you can run gulp build --env=prod and that will create a file called constants.js in your /src/ folder (or wherever you specify). Now include this file in your index.html.

You can now inject the constant ENV anywhere in your services or controllers and reference the variables within.

angular.module('app')

.service('SomeService', function(ENV) {
  // access ENV vars here
});

.controller('SomeCtrl', function($scope, ENV) {
  // access ENV vars here
});
mcranston18
  • 3,760
  • 2
  • 26
  • 32