我一直在尝试创建一组模块,这些模块将在多个项目中使用。
' wsLang'模块是使用提供者和过滤器定义的。
当试图在另一个模块中使用它时,我似乎无法访问' wsTranslationProvider',我不知道为什么!
我已将代码复制到单个HTML页面:
<!DOCTYPE html>
<html lang="en" data-ng-app="test">
<head>
<meta charset="UTF-8">
<title>Angular App</title>
</head>
<body>
<div data-ng-controller="ctrl1 as vm">
<p>{{vm.a | wsTranslate}}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-sanitize.min.js"></script>
<script>
angular.module('wsLang', [])
.provider('wsTranslationProvider', function() {
this.locale = 'en';
this.phrases = {};
this.setLocale = function (locale) {
if (locale.length < 2) return;
this.locale = locale;
};
this.setPhrases = function (phrases, locale) {
if (locale === undefined) locale = this.locale;
this.phrases[locale] = phrases;
};
this.addPhrase = function (key, value, locale) {
if (locale === undefined) locale = this.locale;
this.phrases[locale][key] = value;
};
this.getPhrase = function (key, locale) {
if (locale === undefined) locale = this.locale;
if (this.phrases[locale] !== undefined) {
if (this.phrases[locale][key] !== undefined) {
return this.phrases[locale][key];
}
}
return key;
};
this.$get = function () {
return this;
};
})
.filter('wsTranslate', ['wsTranslationProvider', function(provider) {
return function(input) {
return provider.getPhrase(input);
};
}]);
angular.module('test', ['wsLang'])
.config(function(wsTranslationProvider) {
wsTranslationProvider.setLocale('en');
wsTranslationProvider.addPhrase('test', 'Test');
})
.controller('ctrl1', function() {
var vm = this;
vm.a = 'test';
});
</script>
</body>
</html>
无论我尝试什么,&#39; wsTranslationProvider&#39;在其他模块中无法识别。继续无法实例化模块&#39;错误的&#39;未知提供商:wsTranslationProvider&#39;。
有什么想法吗?
答案 0 :(得分:1)
在名称中定义不带 Provider 后缀的提供程序:
angular.module('wsLang', [])
.provider('wsTranslation', function() {
...
});
出于某种原因(我想稍后调查)使用其他模块中定义的提供程序需要这个。如果您将提供程序更改为在同一 test 模块中定义,那么您的代码也将起作用。