How to create Dynamic factory in Angular js?

狂风中的少年 提交于 2019-12-23 09:33:47

问题


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?


回答1:


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', 
                                '$injector',
                                '$scope',
                                function(service, $injector, $scope) {
    $scope.service1 = service.run('injected.');   
    $scope.service2 = $injector.get('ex2-service').run('dynamically injected');
}]);

Here is the full working fiddle: http://jsfiddle.net/jeremylikness/QM52v/1/

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: http://jsfiddle.net/jeremylikness/G98JD/2/



来源:https://stackoverflow.com/questions/21733661/how-to-create-dynamic-factory-in-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!