Angular Zen
Ideally, we would like to have our NotificationsService service to be provided
with a configuration value in the following manner:
myMod.factory('notificationsService',
function (notificationsArchive, MAX_LEN) {
...
//creation logic doesn't change
});
And then supply configuration values outside of NotificationsService, on a
module level as shown in the following code:
myMod.constant('MAX_LEN', 10);
Constants are very useful for creating services that can be re-used across many
different applications (as clients of a service can configure it at their will). There
is only one disadvantage of using constants, that is, as soon as a service expresses
a dependency on a constant, a value for this constant must be supplied. Sometimes
it would be good to have default configuration values and allow clients to change
them only when needed.
Providers
All the registration methods described so far are just special cases of the most
generic, ultimate version of all of them, provider. Here is the example of
registering the notificationsService service as a provider:
myMod.provider('notificationsService', function () {
var config = {
maxLen : 10
};
var notifications = [];
return {
setMaxLen : function(maxLen) {
config.maxLen = maxLen || config.maxLen;
},
$get : function(notificationsArchive) {
return {
push:function (notification) {
...
if (newLen > config.maxLen) {
...
}