15

I define a customer service named "greeting", but can't get the instance from $injector.get('greeting'). It will throw such error: Unknown provider: greetingProvider <- greeting. So which is the right way to get it? Following is the code:

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');
jason
  • 1,621
  • 6
  • 21
  • 39
  • 2
    You're asking an injector without passing any module. But your greeting service is defined in the myDI module. See http://docs.angularjs.org/api/angular.injector – JB Nizet Jul 27 '13 at 12:08
  • 3
    Most importantly: why are you trying to use `injector` directly? It is very, very rare to play with it outside of a unit test... See also http://stackoverflow.com/q/13400687/1418796 – pkozlowski.opensource Jul 27 '13 at 12:31

1 Answers1

26

You need to create the injector from the module.

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();

Try it here. FIDDLE

zs2020
  • 53,766
  • 29
  • 154
  • 219