简体   繁体   English

动态将ng-controller作为字符串插入模板

[英]Dynamically insert ng-controller in template as string

I have a custom directive and it's template includes an ng-controller directive which needs to be dynamically set. 我有一个自定义指令,它的模板包含需要动态设置的ng-controller指令。 Here is my non working code.... 这是我的无效代码。

angular.module('myDirectives').directive('tabPanel', function() { angular.module('myDirectives')。directive('tabPanel',function(){

return {
    restrict: 'E',
    scope: {
        id: '@?tabId',
        template: '@?',
        controller: '@?'
    },
    controller: 'TabPanelCtrl as tabPanelCtrl',
    transclude: true,
    template: getTemplate
};

function getTemplate(element, attr) {

    if(attr.template && attr.controller){
        return '<tab-panel-inner ng-include="template" ng-controller="controller" ng-transclude></tab-panel-inner>'
    }

    else{
        return '<tab-panel-inner ng-transclude></tab-panel-inner>'
    } 

}

function postLink(scope, element, attr, ctrls) {

    var containerCtrl = ctrls[0];

    // Add container controller to scope if it exists.
    if(containerCtrl){
        scope.tabPanelCtrl.containerCtrl = containerCtrl;
    }

    scope.tabPanelCtrl.initialize();

}

}); });

I use the directive like this: 我使用这样的指令:

<tab-panel tab-id="..." template="..." controller="TestTabFoldersCtrl as testTabFolders"></tab-panel>

The error I get is: 我得到的错误是:

Error: [ng:areq] Argument 'controller' is not a function, got string 错误:[ng:areq]参数'controller'不是函数,得到了字符串

Now, I know it's a string, but surely when using the ng-controller attribute in normal HTML you provide a string to it? 现在,我知道它是一个字符串,但是可以肯定的是,在普通HTML中使用ng-controller属性时,您是否为此提供了字符串?

I have tried changing the template to this: 我尝试将模板更改为此:

return '<tab-panel-inner ng-include="template" ng-controller="{{controller}}" ng-transclude></tab-panel-inner>'

I thought the curly braces might make it evaluate it, but it doesn't help. 我以为花括号可以使它评估它,但没有帮助。 The only thing that works is hard-coding the 唯一有效的方法是硬编码

You just need to concatenate the attribute values into the template string: 您只需要将属性值连接到模板字符串中:

function getTemplate(element, attr) {

    if(attr.template && attr.controller){
        var template ='<tab-panel-inner ng-include="' + attr.template + '"';
            template += ' ng-controller="'+ attr.controller + '" ng-transclude></tab-panel-inner>' 
        return template; 
    }

    else{
        return '<tab-panel-inner ng-transclude></tab-panel-inner>'
    } 

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM