AngularJS-通过字符串获取控制器函数 [英] AngularJS - Get controller function by string

查看:103
本文介绍了AngularJS-通过字符串获取控制器函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ng-include指令,该指令将基于作用域中的某些变量具有动态模板和控制器.目前,我有这样的地图.

I am using the ng-include directive that will have a dynamic template and controller based on some variables in the scope. Currently I have a map like this.

$scope.map = {
    'key1': {
        controller: Ctrl1,
        templateUrl: 'tmpl1.html'
 }, 
'key12': {
        controller: Ctrl2,
    templateUrl: 'tmpl1.html'
    }
}

...

<div ng-include src="map[key].templateUrl" ng-controller="map[key].controller"></div>

但是,我想丢弃此映射,而是通过字符串生成templateUrl和控制器.以下返回控制器 object ,但我需要返回该函数.

However, I would like to discard this map and instead generate the templateUrl and controller via a string. The following returns the controller object but I need the function to be returned.

var ctrlObj = angular.module('moduleName').controller('ControllerName')

编辑1

要澄清:

但是,我想丢弃此映射,而是通过字符串生成templateUrl和控制器

However, I would like to discard this map and instead generate the templateUrl and controller via a string

基本上,我会以某种方式在页面上设置子控制器",以使它成为约定俗成的配置.具有所有子控制器将共享的信息的主控制器:FooCtrl将是主"控制器,而FooBarCtrl,FooBarSubCtrl将是子控制器.我的目标是创建一个将"Bar"解析为"FooBarCtrl"的函数,并从中获取相应的控制器函数.

Basically I would to set up 'sub-controllers' on a page a way so that it would be convention over configuration. A master controller that has information that all the sub-controllers would share: FooCtrl would be the 'master' controller while FooBarCtrl, FooBarSubCtrl would be sub-controllers. My goal would be to make a function that would resolve "Bar" to "FooBarCtrl" and from that grab the appropriate controller function.

推荐答案

我看不到实现这一目标的任何简单方法,但是我可以想象两个潜在的解决方案:

I don't see any trivial way of achieving this, however I can imagine two potential solutions:

  1. 修改ngInclude指令,以便它采用src表达式,对其进行解析以获取控制器名称(模板Foo.html =>控制器FooCtrl),并像在ngView中一样在元素上设置控制器( https://github.com/angular/angular .js/blob/master/src/ng/directive/ngView.js#L149 ):

controller = $controller(current.controller, {$scope: lastScope});
element.contents().data('$ngControllerController', controller);

  • 创建新指令,例如监视src表达式并将控制器链接到元素的方法与第1点相同."ajpaz-controller"的明显好处是无需更改原始ng-include即可完成此操作.会像这样

  • Create new directive e.g. "ajpaz-controller" that watches the src expression and links the controller to the element the same way as in point 1. The obvious advantage is that it can be done without modifying the original ng-include. It would work like this

    <div ng-include src="templateUrl" ajpaz-controller>
    

  • 因此,您只需要将当前templateUrl保留在父控制器中.希望有道理;)

    So you would have to only keep the current templateUrl in your parent controller. Hope that makes sense;)

    这篇关于AngularJS-通过字符串获取控制器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆