angularjs – 在父指令中附加子指令

前端之家收集整理的这篇文章主要介绍了angularjs – 在父指令中附加子指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个父指令,我想在链接函数中动态添加子指令.子指令^需要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','$sce',$sce) {
  return {
    restrict: 'E',scope: {},require: '^myInput',attr,myCtrl) {
      myCtrl.addKey(attr.code,attr.response);

      // ...
    },template: '<div class="key"><span ng-bind-html="key"></span></div>'
  };
}]);
将compile-append操作的顺序更改为append-compile:
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.因此你得到的错误.

另外我建议将您的指令的名称从camelCase更改为snake-case:

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

那么编译部分也会改变:

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

猜你在找的Angularjs相关文章