If you need to enhance your service generator, consider annotating it in this manner. The process involves taking the module and extension, then adding an annotation for a dependency on the "echo" service (a sample service created for echoing text and logging it to the console), enabling the generated service to utilize it:
enhanceService = function(module, identifier) {
module.factory(identifier+'-service', ['echo', function(echo) {
return {
run: function(msg) {
return echo.echo(identifier + ": " + msg);
}
};
}]);
};
You can proceed by creating a number of dynamic services:
enhanceService(app, 'ex1');
enhanceService(app, 'ex2');
For injection, there are two approaches. If you have a known convention, you can pass it along with the annotation like ext1 is demonstrated. Otherwise, retrieve an instance of the $injector and obtain it that way.
app.controller("myController", ['ex1-service',
'$injector',
'$scope',
function(service, $injector, $scope) {
$scope.service1 = service.run('injected.');
$scope.service2 = $injector.get('ex2-service').run('dynamically injected');
}]);
To see the complete functioning demo, visit this fiddle: http://jsfiddle.net/jeremylikness/QM52v/1/
Update: To dynamically create the service post initialization of the module, a few tweaks are necessary. Instead of attempting to register the module, just return an annotated array. The dependencies come first in the parameters, followed by the registration function:
enhanceService = function(identifier) {
return ['echo', function(echo) {
console.log("in service factory");
return {
run: function(msg) {
return echo.echo(identifier + ": " + msg);
}
};
}];
};
Then, obtain a reference to the array and invoke instantiate on the $injector to set up the wiring with dependencies:
var fn = enhanceService('ex2');
$scope.service2 = $injector.instantiate(fn).run('dynamically injected');
Check out the fiddle for this version here: http://jsfiddle.net/jeremylikness/G98JD/2/