私はまだ Angularjs のデビュタントです。コントローラーに (作成した) サービスの依存関係を動的に挿入したいと考えています。
しかし、依存関係のあるサービスをコーディングすると、次のエラーが発生しました。
エラー: 不明なプロバイダー: $windowProvider <- $window <- base64
これはコントローラーのコードです。
var base64 = angular.injector(['servicesModule']).get('base64');
console.log("base64", base64.encode("my text will be encoded"));
このコードは機能します:
var servicesModule = angular.module('servicesModule', []);
servicesModule.factory('base64', function() {
return {
name: 'base64',
readonly: false,
encode: function(input) {
return window.btoa(input);
},
decode: function(input) {
return window.atob(input);
}
};
});
このコードは機能しません:
var extModule = angular.module('ext', []);
extModule.factory('base64', ['$window', function($window) {
return {
name: 'base64',
readonly: false,
encode: function(input) {
return $window.btoa(input);
},
decode: function(input) {
return $window.atob(input);
}
};
}]);
別の問題は、サービスがコントローラーと同じモジュールにある場合です。モジュールに依存関係がある場合、機能しません (モジュール構成に $routeProvider 依存関係があります) :
エラー: 不明なプロバイダー: mainModule からの $routeProvider
var mainModule = angular.module('main', [],
function($routeProvider, $locationProvider) {
//Some routing code
}
);
JSフィドル
依存関係のある同じモジュール (コントローラー + サービス) : http://jsfiddle.net/yrezgui/YedT2/
依存関係のある別のモジュール: http://jsfiddle.net/yrezgui/YedT2/4/
依存関係のない別のモジュール: http://jsfiddle.net/yrezgui/YedT2/5/