我定义了一个名为“greeting”的客户服务,但无法从$ injector.get('greeting')获取实例。它会抛出这样的错误:未知提供者:greetingProvider< - greeting 。那么这是获得它的正确方法?以下是代码:
var app = angular.module('myDI', []);
app.config(function($provide){
$provide.provider('greeting', function(){
this.$get = function(){
return function(name) {
console.log("Hello, " + name);
};
};
});
});
var injector = angular.injector();
var greeting = injector.get('greeting');
greeting('Ford Prefect');
答案 0 :(得分:26)
您需要从模块创建注射器。
var app = angular.module('myDI', []);
app.config(function($provide){
$provide.provider('greeting', function(){
this.$get = function(){
return function(name) {
console.log("Hello, " + name);
};
};
});
});
var injector = angular.injector(['myDI', 'ng']); //Add this line
var greeting = injector.get('greeting');
greeting('Ford Prefect');
var injector = angular.injector();
在这里试试。 FIDDLE