我如何在角度中使用常数,我想通过工厂附加一个恒定值。请检查以下代码
/ * 在app模块中附加常量的工厂 * /
'use strict';
define(['app'], function (app) {
var traslationParams = ['$resource'];
var translationFactory = function (resource) {
return {
attachTranslator: function (language) {
var languageFilePath = applicationUrl.clientUrl + '/translation/translation_' + language + '.json';
resource(languageFilePath).get(function (data) {
app.constant('languagePack', data); // registering constant
});
}
}
}
translationFactory.$inject = traslationParams;
app.factory('translationFactory', translationFactory);
});
// 我正在执行工厂api以使用以下代码注册常量
app.run([ 'translationFactory', function ( translationFactory) {
translationFactory.attachTranslator('da');}]);
// 在控制器中使用常量
var companyController = function (languagePack) {
scope.languagePack = languagePack;
console.log(languagePack);
}
但我在控制器中收到错误
Error: [$injector:unpr] Unknown provider: languagePackProvider <- languagePack <- companyController
答案 0 :(得分:0)
将languagepack添加为translationFactory属性并将转换输出保存到此属性。通过控制器中的服务进一步引用该属性。
'use strict';
define(['app'], function (app) {
var traslationParams = ['$resource'];
var translationFactory = function (resource) {
return {
languagePack: {},
attachTranslator: function (language) {
var trans = this;
var languageFilePath = applicationUrl.clientUrl + '/translation/translation_' + language + '.json';
resource(languageFilePath).get(function (data) {
//app.constant('languagePack', data); // registering constant
trans.languagePack = data
});
}
}
}
translationFactory.$inject = traslationParams;
app.factory('translationFactory', translationFactory);
});
app.run([ 'translationFactory', function ( translationFactory) {
translationFactory.attachTranslator('da');}]);
var companyController = function (translationFactory) {
scope.languagePack = translationFactory.languagePack;
console.log(scope.languagePack);
}