问题描述
在我的项目中,我必须在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?
推荐答案
您可以像这样注释您的服务生成器.它获取模块和扩展,然后注释对echo"服务的依赖(只是我定义的一个示例服务,用于回显文本并将其记录到控制台),以便生成的服务可以使用它:
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');
最后有两种注入方式.如果您知道您的约定,您可以将其与注释一起传递,如 ext1 所示.否则,只需获取 $injector 的一个实例并以这种方式获取它.
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');
}]);
这是完整的工作小提琴:http://jsfiddle.net/jeremylikness/QM52v/1/
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);
}
};
}];
};
然后你得到一个对数组的引用并在 $injector 上调用实例化来连接它:
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');
这是该版本的小提琴:http://jsfiddle.net/jeremylikness/G98JD/2/
这篇关于如何在 Angular js 中创建动态工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!