Reputation: 367
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?
Upvotes: 1
Views: 1321
Reputation: 4790
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
});
Upvotes: 5