我对这个主题有点晚了,但是如果你使用Grunt,我已经在grunt-ng-constant
上取得了巨大的成功。
在我的配置部分看起来像ngconstant
Gruntfile.js
ngconstant: {
options: {
name: 'config',
wrap: '"use strict";\n\n{%= __ngModule %}',
space: ' '
},
development: {
options: {
dest: '<%= yeoman.app %>/scripts/config.js'
},
constants: {
ENV: 'development'
}
},
production: {
options: {
dest: '<%= yeoman.dist %>/scripts/config.js'
},
constants: {
ENV: 'production'
}
}
}
使用的任务如下所示ngconstant
grunt.registerTask('server', function (target) {
if (target === 'dist') {
return grunt.task.run([
'build',
'open',
'connect:dist:keepalive'
]);
}
grunt.task.run([
'clean:server',
'ngconstant:development',
'concurrent:server',
'connect:livereload',
'open',
'watch'
]);
});
grunt.registerTask('build', [
'clean:dist',
'ngconstant:production',
'useminPrepare',
'concurrent:dist',
'concat',
'copy',
'cdnify',
'ngmin',
'cssmin',
'uglify',
'rev',
'usemin'
]);
所以运行将生成一个文件,看起来像grunt server
config.js
app/scripts/
"use strict";
angular.module("config", []).constant("ENV", "development");
最后,我声明了对任何需要它的模块的依赖关系:
// the 'config' dependency is generated via grunt
var app = angular.module('myApp', [ 'config' ]);
现在,我的常量可以根据需要注入依赖关系。例如,
app.controller('MyController', ['ENV', function( ENV ) {
if( ENV === 'production' ) {
...
}
}]);