在父指令中附加child指令

jim*_*mmy 17 angularjs angularjs-directive

我有一个父指令,我想在链接函数中动态添加子指令.子指令^需要parentDirective.我可以添加任何html元素,但是一旦我尝试$ compile我的子指令,我得到以下错误,它无法找到所需的控制器.如果我手动添加子指令它完美地工作.

错误:

Error: [$compile:ctreq] Controller 'myInput', required by directive 'myKey', can't be found!
Run Code Online (Sandbox Code Playgroud)

添加元素后,我的模板应如下所示:

<myInput>
 <myKey></myKey> <-- added dynamically
 <myKey></myKey> <-- added dynamically
 <myKey></myKey> <-- added dynamically
  ....
</myInput>
Run Code Online (Sandbox Code Playgroud)

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>'
  };
}]);
Run Code Online (Sandbox Code Playgroud)

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>'
  };
}]);
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 24

将compile-append操作的顺序更改为append-compile:

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

显然,在这种情况下(定位父元素指令),正在编译的新元素已经在DOM中.

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

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

<my-input>
    <my-key></my-key>
</my-input>
Run Code Online (Sandbox Code Playgroud)

然后编译部分也会改变:

angular.element('<my-key code="'+ key +'" response="'+ value.response +'"></my-key >');
Run Code Online (Sandbox Code Playgroud)