If you're looking for a thorough explanation on providers, factories, and services in AngularJS, the official documentation is a great resource to reference.
In simple terms, when creating a provider, you should expose necessary methods along with the $get
method. During configuration, you can utilize these methods before the system injects any dependencies, ultimately calling the $get
method.
I've put together a basic Plnkr demo to demonstrate this process:
1. Creating the Provider
app.provider('myService', function() {
var configuredValue;
this.setValue = function(val) {
configuredValue = val;
};
this.$get = function() {
return {
valueSettedByTheConfig: configuredValue
};
};
});
This code establishes the provider for the myService
service, allowing access to a setValue
configuration method akin to $locationProvider.html5Mode
or $routeProvider.otherwise
.
2. Configuration Step
app.config(function(myServiceProvider) {
myServiceProvider.setValue('my configured value');
});
During module configuration, we set values using the exposed setValue
method before its usage.
Note that we are injecting the provider (myService*Provider*
) here because only providers can be injected during the configuration phase, not services.
3. Implementation in Controller
app.controller('MainCtrl', function($scope, myService) {
$scope.name = myService.valueSettedByTheConfig;
});
Finally, when working within a controller, simply inject the service which will trigger the provider's $get
method post-configuration to create an instance of the service.