我有一个父指令,在链接函数中我想动态添加子指令。 子指令^需要parentDirective。 我能够添加任何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>'
};
}]);
parentNode
属性为null
)。当 Angular 查找^myInput
时,它会沿着 DOM 树向上遍历,直到找到一个具有所需指令的节点。在我们的情况下,它立即失败,因为该元素没有单个父节点。 - dfsq