おそらく、ディレクティブコントローラでルート変更が発生したときに作成されるコントローラを混乱させることでしょう。このセクションでは、ディレクティブコントローラについてのみ説明しています。したがって、同じHTML要素に2つのディレクティブがある場合、それらのディレクティブはコントローラを要求することによって通信できます。
その良い例は、ng-model
と通信する必要のあるディレクティブを作成する場合です。
myApp.directive('myDirective', function() {
return {
require: 'ngModel',
link: function($scope, elem, attrs, ngModelCtrl) {
// Here you can listen to different DOM events, and
// call ngModelCtrl when the model value needs to update
}
}
});
そしてHTML::
<input type="text" ng-model="myModel" my-directive>
あなたのディレクティブは次のように、そのあなたのディレクティブ関数が返すオブジェクトでそれを実装することにより、コントローラを公開することができng-model
は、コントローラを公開しているので、あなたはこのようにそれを必要とすることができますこの:
myApp.directive('myDirective1', function() {
return {
link: function($scope, elem, attrs) {
},
controller: function() {
this.sayHello = function() {
alert("hello!");
}
}
}
});
myApp.directive('myDirective2', function() {
return {
require: 'myDirective1',
link: function($scope, elem, attrs, myDirective1Ctrl) {
myDirective1Ctrl.sayHello();
}
}
});
そしてHTML:
<input type="text" my-directive2 my-directive1>
また、このように、require: '^myParentDirective'
を書き込むことによって、親指令からの指示のコントローラを必要とすることができます
myApp.directive('myDirective1', function() {
return {
link: function($scope, elem, attrs) {
},
controller: function() {
this.sayHello = function() {
alert("hello!");
}
}
}
});
myApp.directive('myDirective2', function() {
return {
require: '^myDirective1',
link: function($scope, elem, attrs, myDirective1Ctrl) {
myDirective1Ctrl.sayHello();
}
}
});
とHTMLを:
<div my-directive1>
<div my-directive2></div>
</div>
チェック[この質問](のhttp://のstackoverflowを。 com/questions/14915332/what-does-require-of-directive-definition-object-take)と[this example](http://jsfiddle.net/bmleite/GSZkJ/)を参照してください。 – bmleite
良い質問に気をつけてください。 – Stewie
[その例](http://jsfiddle.net/bmleite/GSZkJ/)は少し誤解を招く。一見すると、コントローラインスタンスの 'num'プロパティを共有しているように見えます。実際に起こっているのは、内側ディレクティブが、外側ディレクティブコントローラインスタンスから内側と外側の両方のスコープオブジェクトにインクリメント機能をコピーすることだけです。それはテンプレートから呼び出されたときにthis ==スコープオブジェクトになります。これらの点を説明しようとするこの[調整された例](http://jsfiddle.net/fess/a68Ra/)を参照してください。 –