6

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?

4

1 回答 1

9

您可以像这样注释您的服务生成器。它获取模块和扩展,然后注释对“回显”服务的依赖(只是我定义的一个示例服务,用于回显文本并将其记录到控制台),以便生成的服务可以使用它:

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

然后你可以做一些动态服务:

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

最后,有两种注入方式。如果您知道您的约定,则可以将其与注释一起传递,因为显示了 ext1。否则,只需获取 $injector 的实例并以这种方式获取它。

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');
}]);

这是完整的工作小提琴:http: //jsfiddle.net/jeremylikness/QM52v/1/

更新:如果要在模块初始化后动态创建服务,只需稍作改动。与其尝试注册模块,不如简单地返回一个带注释的数组。第一个参数是依赖项,最后一个是要注册的函数:

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

然后你得到一个对数组的引用并在 $injector 上调用实例化来将它与依赖项连接起来:

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

这是该版本的小提琴:http: //jsfiddle.net/jeremylikness/G98JD/2/

于 2014-02-12T18:14:10.010 回答