最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create Dynamic factory in Angular js? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Feb 12, 2014 at 16:25 pashapluspashaplus 3,7162 gold badges27 silver badges25 bronze badges 2
  • Can you offer more insight than "this is not working"? – Marc Commented Feb 12, 2014 at 16:30
  • @Marc: hi marc, i mean, if i put the break point at above return statement(return existingService(modId);) the control is not reaching to that break point,though i called createDynamicFactory function. – pashaplus Commented Feb 12, 2014 at 17:01
Add a ment  | 

1 Answer 1

Reset to default 9

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/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/jeremylikness/G98JD/2/

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>