How should I make configurable modules in AngularJS
It sounds like you're looking for a provider.
You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.
Here's a very basic example of a provider:
myMod.provider('greeting', function() { var text = 'Hello, '; this.setText = function(value) { text = value; }; this.$get = function() { return function(name) { alert(text + name); }; };});
This creates a new service, just like you might with myMod.service
or myMod.factory
, but provides an additional API that is available at config time—namely, a setText
method. You can get access to the provider in config
blocks:
myMod.config(function(greetingProvider) { greetingProvider.setText("Howdy there, ");});
Now, when we inject the greeting
service, Angular will call the provider's $get
method (injecting any services it asks for in its parameters) and gives you whatever it returns; in this case, $get
returns a function that, when called with a name, will alert the name with whatever we've set with setText
:
myMod.run(function(greeting) { greeting('Ford Prefect');});// Alerts: "Howdy there, Ford Prefect"
This is exactly how other providers, like $httpProvider
and $routeProvider
work.
For more information on providers and dependency injection in general, check out this SO question on dependency injection.