How to create Dynamic factory in Angular js?


In my project i have to create dynamic factory in angular js with dynamic factory name like below

  function createDynamicFactory(modId) {
     return myModule.factory(modId + '-existingService', function (existingService) {
        return existingService(modId);

I want to get new factory with dynamic name , when i called this function. unfortunately this is not working. how can i achieve this? and how to inject in my controller or in directive dynamically?

Problem courtesy of: pashaplus


You can annotate your service generator like this. It takes the module and extension and then annotates a dependency on the "echo" service (just an example service I defined to echo back text and log it to the console) so the generated service can use it:

makeService = function(module, identifier) {
    module.factory(identifier+'-service', ['echo', function(echo) {
            return {
                run: function(msg) {
                    return echo.echo(identifier + ": " + msg);

Then you can make a few dynamic services:

makeService(app, 'ex1');
makeService(app, 'ex2');

Finally, there are two ways to inject. If you know your convention you can pass it in with the annotation as the ext1 is shown. Otherwise, just get an instance of the $injector and grab it that way.

app.controller("myController", ['ex1-service', 
                                function(service, $injector, $scope) {
    $scope.service1 ='injected.');   
    $scope.service2 = $injector.get('ex2-service').run('dynamically injected');

Here is the full working fiddle:

Updated: if you want to create the service dynamically after the module is initialized, it's a few slight changes. Instead of trying to register the module, simply return an annotated array. The first parameters are the dependencies and the last is the function to register:

makeService = function(identifier) {
    return ['echo', function(echo) {
        console.log("in service factory");
            return {
                run: function(msg) {
                    return echo.echo(identifier + ": " + msg);

Then you get a reference to the array and call instantiate on the $injector to wire it up with dependencies:

var fn = makeService('ex2');
$scope.service2 = $injector.instantiate(fn).run('dynamically injected');

Here's the fiddle for that version:

Solution courtesy of: Jeremy Likness


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.