Angular无法在指令

时间:2015-07-05 01:48:16

标签: javascript angularjs angularjs-directive

我正在尝试创建一系列通过控制器进行通信的指令。这就是我现在所拥有的:

angular.module('drmApp')
  .directive('formInput', function () {
    return {
      templateUrl: 'views/directives/forminput.html',
      restrict: 'E',
      controller: 'ForminputCtrl',
      controllerAs: 'ctrl',
      bindToController: true,
      transclude: true,
      scope: {
        model: '=',
        errors: '=',
        property: '@',
        label: '@',
        form: '=?',
      },
      link: function postLink(scope, element, attrs, ctrl, $transcludeFn) {
        console.log($transcludeFn());
      }
    };
  })
  .directive('formInputValidationSummary', function() {
    return {
      restrict: 'E',
      require: '^formInput',
      transclude: true,
      link: function postLink(scope, element, attrs, ctrl, $transcludeFn) {
        ctrl.setValidationSummary($transcludeFn);
      }
    }
  })
  .directive('formInputContent', function() {
    return {
      restrict: 'E',
      require: '^formInput',
      transclude: true,
      link: function postLink(scope, element, attrs, ctrl, $transcludeFn) {
        ctrl.setInput($transcludeFn);
      }
    }
  });

HTML标记:

<form-input model="entity"
    label="{{ 'WYKONAWCA_COLOR' | translate }}"
    errors="errors"
    property="color"
    form="form">
    <form-input-content>
        <input colorpicker="rgb" ng-model="model.color" type="text">
    </form-input-content>
</form-input>

可悲的是,目前我收到了这个错误:

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

我正在使用v1.4系列的最新角度。此外,这不适用于角度~1.3。有什么我忘了的吗?我是否误解了指令功能?

1 个答案:

答案 0 :(得分:1)

由于您正在转录transclude: true,因此Angular会将已转化的内容从DOM中删除 - 因此,<form-input-content>现在不是<form-input>的子项。

然后,当您调用transclude函数时,这将链接该指令 - 并且当时它抱怨无法找到父formInput控制器。

转换时,请务必将已转录的内容放回DOM:

link: function postLink(scope, element, attrs, ctrl, $transcludeFn) {
   $transcludeFn(function(transcludedContentClone){
      // this happens prior to linking of transcluded content
      element.append(transcludedContentClone);
   });

   // ...
}