我一直在尝试创建一组模块,这些模块将在多个项目中使用。
定义了"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>
无论我尝试什么,"wsTranslationProvider"在其他模块中都无法识别。继续获取"未能实例化模块"错误,错误为"未知提供程序:wsTranslationProvider"。
有什么想法吗?
定义名称中没有provider后缀的提供者:
angular.module('wsLang', [])
.provider('wsTranslation', function() {
...
});
出于某种原因(我想稍后研究),使用其他模块中定义的提供程序需要这样做。如果您将提供程序更改为在同一测试模块中定义,那么您的代码也可以工作。