親ディレクティブから子ディレクティブを要求できないのはなぜですか?

StackOverflow https://stackoverflow.com//questions/21005911

  •  20-12-2019
  •  | 
  •  

質問

これは... プランクル このエラーをスローします:

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

私はこれを回避することができますが、これが設計上のものであるかどうか、そしてなぜ(単一の親と複数の子のこと)かどうか興味がありますか?私はこの制限についての言及は見ていません $ng。ドキュメントをコンパイルする.

役に立ちましたか?

解決

これが実装されていない理由はパフォーマンスです。DOMを横断することは、可能な一致のために各子ブランチをチェックするよりもはるかに高速です。このため、推奨される方法は、子要素に親にステータスを通知させることです。

これはディレクティブではなく、関連するコントローラインスタンスを介して行われることに注意してください。

私はあなたのplunkを更新しました 作業例

angular.module('foo', [])

.directive('parentDirective', function() {
  return {
    controller: function($scope) {

      $scope.childs = {};

      this.registerChild = function(child) {
        $scope.childs[child.name] = child;
      };
    },
    link: function(scope, element, attrs) {}
  };
})

.directive('childDirective', function() {
  return {
    controller: function($scope) {},
    require: ['^parentDirective', 'childDirective'],
    link: function($scope, $element, $attrs, $ctrls) {

      var parent = $ctrls[0];
      var child = $ctrls[1];

      child.name = $attrs.childDirective;

      parent.registerChild(child);
    }
  };
});

他のヒント

私がAngularで何もこれを許可していない限り、子ディレクティブを必要とすることはできません。子からの親ディレクティブのみを必要とすることができます。

require: '^parentDirectiveName'

または兄弟ディレクティブ、によって

require: 'siblingDirectiveName'

そうです、これは設計によるものか、少なくとも機能の欠如によるものです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top