它看起來像咕嚕-NG-不斷創建新的模塊文件來定義常數。除了將包含這些常量的模塊聲明爲依賴項之外,您不必在應用程序的JS文件中煩擾它。
以下被視爲是對的documentation of grunt-ng-constant
grunt.initConfig({
ngconstant: {
options: {
name: 'config',
dest: 'config.js',
constants: {
title: 'grunt-ng-constant',
debug: true
}
},
dev: {
constants: {
title: 'grunt-ng-constant-beta'
}
},
prod: {
constants: {
debug: false
}
},
}
});
的例子配置在options
部分,指定模塊的名稱,文件的模塊被寫入和一般組常量。它的工作原理是這樣,
options: {
name: 'config',
dest: 'config.js',
constants: {
title: 'grunt-ng-constant',
debug: true
}
}
上面的代碼將成爲,
/*File: config.js*/
angular.module('config', [])
.constant('title', 'grunt-ng-constant')
.constant('debug', true);
要更改基於您的方案(開發/生產)的常量,你會使用不同的任務集。這裏是dev
和prod
節開始發揮作用
考慮到你正在使用ng-boilerplate,在gruntfile.js你有任務建立和編譯。構建任務在開發過程中使用,並且編譯可讓您的應用程序準備好投入生產。
在build task
中,您將添加ngconstant:dev
,並在compile task
中添加ngconstant:prod
。
grunt.registerTask('build', ['clean', 'html2js', 'otherTasksComeHere', 'ngconstant:dev']);
grunt.registerTask('compile', ['clean', 'html2js', 'otherTasksComeHere', 'ngconstant:prod']);
爲您的方案中的代碼將如下:
/*gruntfile.js*/
grunt.initConfig({
ngconstant: {
options: {
name: 'lelylan.client.config',
dest: 'config.js',
values: {
endpoint : 'http://localhost:8000'
}
},
dev: {
debug: true
},
prod: {
endpoint: 'http://www.production-server.com/',
debug: false
}
},
});
grunt.registerTask('build', ["ngconstant:dev"]);
grunt.registerTask('compile', ["ngconstant:prod"]);
grunt.registerTask.('default', ["build", "compile"]);
/*app.js*/
var app = angular.module('app', ['lelylan.dashboards.device', 'leylan.client.config', 'ngMockE2E']);
app.controller("appCtrl", ["$scope", "$http", "endpoint",
function($scope, $http, endpoint) {
$scope.submit = function(formData) {
$http.post(endpoint+'/processform.php', formData);
}
}]);
現在,這一切取決於你是否運行grunt build
或grunt compile
。 使用grunt
命令時將運行默認任務。
謝謝@sylwester。我在同一點。我很想知道如果我可以使用服務的常量(在我的情況下爲ENV.endpoint)而不是設置端點字符串。 –