I was able to solve this very same problem. I have development, testing and production environments and they each need to connect to different API end points. I was able to accomplish this using a grunt plugin called grunt-ng-constant
Basically once you install the plugin, modify your Gruntfile and inside the grunt.initConfig
add something like this:
ngconstant: {
// Options for all targets
options: {
space: ' ',
wrap: '"use strict";\n\n {%= __ngModule %}',
name: 'config',
},
// Environment targets
development: {
options: {
dest: '<%= yeoman.app %>/scripts/config.js'
},
constants: {
ENV: {
name: 'development',
apiEndpoint: 'http://your-development.api.endpoint:3000'
}
}
},
production: {
options: {
dest: '<%= yeoman.dist %>/scripts/config.js'
},
constants: {
ENV: {
name: 'production',
apiEndpoint: 'http://api.livesite.com'
}
}
}
},
Register the Grunt task like so:
grunt.registerTask('serve', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'ngconstant:development', // ADD THIS
'bower-install',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
Now every time you run grunt serve
it will generate a config.js file that holds your development constants. You can configure different tasks such as grunt testing
or grunt production
to generate the testing or production constants instead.
Finally you add the config.js to your index.html like so:
<script src="/scripts/config.js" />
And register the config module in your app:
var app = angular.module('myApp', [ 'config' ]);
In your controller you can get your "environment" variables like this:
angular.module('myApp')
.controller('MainCtrl', function ($scope, $http, ENV) { // ENV is injected
$scope.login = function() {
$http.post(
ENV.apiEndPoint, // Our environmental var :)
$scope.yourData
).success(function() {
console.log('Cows');
});
};
});
With this approach you can easily automate the entire deployment pipeline. You can have a CI server push your changes to the appropriate servers and build the correct version of your app.
Here's a very helpful resource for you to read and from which I took the code samples: http://mindthecode.com/how-to-use-environment-variables-in-your-angular-application
Hope this helps you!