2016-02-09 28 views
11

the docs(具体的には、ディレクティブとコンポーネントを比較するテーブル)によれば、角度コンポーネントは他のディレクティブを必要とします(またはコンポーネントのみですか?ただし、コンポーネントには、必要なコントローラにアクセスできるリンク機能がありません。 The sourceは、ドキュメントに反して、コンポーネントを作成するときに「要求」を使用できないことを示唆しているようです。それは本当ですか?角度コンポーネントで 'require'を使用する

答えて

17

引用元は古くなっています。 1.5.0以降、他のコンポーネントのコンポーネントコントローラcan be required(ディレクティブにも同じことが適用されます)。

012からの例shows the way how the components and directives should interactは、補助なしでlinkからのものです。

require object and bindToControllerを一緒に使用すると、必要なコントローラインスタンスが現在のコントローラにプロパティとして割り当てられます。

これはディレクティブリンク中に発生するため、必要なコントローラはコントローラコンストラクタで使用できないため、$onInit magic methodが存在します。存在する場合、it is executed right after adding required controllersthis

両方

app.directive('someDirective', function() { 
    return { 
    scope: {}, 
    bindToController: {}, 
    controllerAs: 'someDirective', 
    require: { 
     anotherDirective: '^anotherDirective' 
    }, 
    controller: function ($scope) { 
     console.log("You don't see me", this.anotherDirective); 

     this.$onInit = function() { 
     console.log("Now you do", this.anotherDirective); 
     }; 
    } 
    } 
}); 

app.component('someComponent', { 
    controllerAs: 'someComponent', 
    require: { 
    anotherDirective: '^anotherDirective' 
    }, 
    controller: function ($scope) { 
    console.log("You don't see me", this.anotherDirective); 

    this.$onInit = function() { 
     console.log("Now you do", this.anotherDirective); 
    }; 
    } 
}); 

宣言スタイルはボンネットの下同等であり、1.5で互換的に使用することができ、componentは簡潔なものです。

関連する問題