2014-11-06 102 views
15

我有一个父指令,我想在链接函数中动态添加子指令。 子指令^要求父指令。 我能够添加任何HTML元素,但只要我试图$编译我的子指令我收到以下错误,它无法找到所需的控制器。如果我手动添加子指令,它完美的作品。在父指令中附加子指令

错误:

Error: [$compile:ctreq] Controller 'myInput', required by directive 'myKey', can't be found! 

我的模板应该是这样的添加元素后:

<myInput> 
<myKey></myKey> <-- added dynamically 
<myKey></myKey> <-- added dynamically 
<myKey></myKey> <-- added dynamically 
    .... 
</myInput> 

myInput指令:

angular.module('myModule').directive('myInput', ['$log', '$templateCache', '$compile', function($log, $templateCache, $compile) { 
    return { 
    restrict: 'E', 
    transclude: true, 
    scope: { 
     service: '=',   // expects a stimulus object provided by the tatoolStimulusService 
     onkeydown: '&'   // method called on key press 
    }, 
    controller: ['$scope', function($scope) { 
     this.addKey = function(keyCode, value) { 
     $scope.service.addInputKey(keyCode, { givenResponse: value }); 
     }; 
    }], 
    link: function (scope, element, attr) { 

     // add keys directives 
     angular.forEach(scope.service.registeredKeyInputs, function(value, key) { 
     var keyEl = angular.element(
      $compile('<myKey code="'+ key +'" response="'+ value.response +'"></myKey >')($rootScope)); 
     element.children(":first").append(keyEl); 
     }); 

    }, 
    template: '<div ng-transclude></div>' 
    }; 
}]); 

的myKey指令:

angular.module('myModule').directive('myKey', ['$log', '$sce', function($log, $sce) { 
    return { 
    restrict: 'E', 
    scope: {}, 
    require: '^myInput', 
    link: function (scope, element, attr, myCtrl) { 
     myCtrl.addKey(attr.code, attr.response); 

     // ... 
    }, 
    template: '<div class="key"><span ng-bind-html="key"></span></div>' 
    }; 
}]); 

回答

22

更改编译追加的操作顺序追加编译:

var keyEl = angular.element('<myKey code="'+ key +'" response="'+ value.response +'"></myKey>'); 
element.append(keyEl); 
$compile(keyEl)(scope); 

显然,这是在这种情况下(定位父元素指令)重要的是,新的元素被编译为已经在DOM。

除非将DOM元素附加到DOM,否则它没有父项(其parentNode属性为null)。当Angular查找^myInput时,它会遍历DOM树,直到找到具有所需指令的节点。如果该元素不在DOM中,则该搜索立即失败,因为元素没有单个parentNode。因此你得到的错误。

此外,我建议从驼峰改变你的指令名蛇情况:

<my-input> 
    <my-key></my-key> 
</my-input> 

然后编译部分也将发生变化:

angular.element('<my-key code="'+ key +'" response="'+ value.response +'"></my-key >'); 
+0

完美的作品,并没有甚至意义(尽管关于此的文档将有所帮助)。我只是在帖子中使用虚拟名称,但你当然对蛇的情况是正确的。再次感谢。 – jimmy 2014-11-07 00:16:17

+1

我不了解文档,但很容易理解。在DOM元素附加到DOM树之前,它不会有**父项(它的'parentNode'属性是'null')。当Angular查找'^ myInput'时,它会遍历DOM树,直到找到具有所需指令的节点。在我们的例子中,它立即失败,因为元素没有单个父节点。 – dfsq 2014-11-07 07:04:07