You give AngularJS a function, AngularJS will cache and inject the return value when the factory is requested.
Example:
app.factory('factory', function() {
var name = '';
// Return value **is** the object that will be injected
return {
name: name;
}
})
Usage:
app.controller('ctrl', function($scope, factory) {
$scope.name = factory.name;
});
You give AngularJS a function, AngularJS will call new to instantiate it. It is the instance that AngularJS creates that will be cached and injected when the service is requested. Since new was used to instantiate the service, the keyword this is valid and refers to the instance.
Example:
app.service('service', function() {
var name = '';
this.setName = function(newName) {
name = newName;
}
this.getName = function() {
return name;
}
});
Usage:
app.controller('ctrl', function($scope, service) {
$scope.name = service.getName();
});
You give AngularJS a function, and AngularJS will call its $get
function. It is the return value from the $get
function that will be cached and injected when the service is requested.
Providers allow you to configure the provider before AngularJS calls the $get
method to get the injectible.
Example:
app.provider('provider', function() {
var name = '';
this.setName = function(newName) {
name = newName;
}
this.$get = function() {
return {
name: name
}
}
})
Usage (as an injectable in a controller)
app.controller('ctrl', function($scope, provider) {
$scope.name = provider.name;
});
Usage (configuring the provider before $get
is called to create the injectable)
app.config(function(providerProvider) {
providerProvider.setName('John');
});