Use $provide
to register new providers with the $injector
. The providers are the factories for the instance.
The providers share the same name as the instance they create with the Provide
suffixed to them.
A provider is an object with a $get()
method. The injector calls the $get
method to create a new instance of
a service. The Provider can have additional methods which would allow for configuration of the provider.
function GreetProvider() { var salutation = 'Hello'; this.salutation = function(text) { salutation = text; }; this.$get = function() { return function (name) { return salutation + ' ' + name + '!'; }; }; } describe('Greeter', function(){ beforeEach(module(function($provide) { $provide.service('greet', GreetProvider); }); it('should greet', inject(function(greet) { expect(greet('angular')).toEqual('Hello angular!'); })); it('should allow configuration of salutation', function() { module(function(greetProvider) { greetProvider.salutation('Ahoj'); }); inject(function(greet) { expect(greet('angular')).toEqual('Ahoj angular!'); }); )}; });
A short hand for configuring services if only $get
method is required.
name – {string} –
The name of the instance. NOTE: the provider will be available under name + 'Provide'
key.
$getFn – {function()} –
The $getFn for the instance creation. Internally this is a short hand for
$provide.service(name, {$get:$getFn})
.
Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
name – {string} –
The name of the instance. NOTE: the provider will be available under name + 'Provide'
key.
provider – {(Object|function())} –
If the provider is:
Object
: then it should have a $get
method. The $get
method will be invoked using
$injector.invoke()
when an instance needs to be created.Constructor
: a new instance of the provider will be created using
$injector.instantiate()
, then treated as object
.A short hand for configuring services if the $get
method is a constant.
name – {string} –
The name of the instance. NOTE: the provider will be available under name + 'Provide'
key.
value – {function()} –
The $getFn for the instance creation. Internally this is a short hand for
$provide.service(name, {$get:function(){ return value; }})
.