지시문 컨트롤러로 경로가 변경 될 때 생성되는 컨트롤러를 혼동하는 것일 수도 있습니다. 이 섹션은 지시어 컨트롤러에 대해서만 이야기하기 때문에 동일한 HTML 요소에 두 개의 지시문이 있으면 서로 컨트롤러를 요구함으로써 통신 할 수 있다는 것을 의미합니다.
좋은 예는 ng-model
과 통신해야하는 지시문을 만드는 경우입니다. 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>
귀하의 지시어는 같은 물체에 당신의 지시 기능 반환을 구현하여 컨트롤러를 노출 할 수 있습니다 이 :
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 : // 유래합니다. com/questions/14915332/what-does-require-of-directive-definition-object-take) 및 [이 예제] (http://jsfiddle.net/bmleite/GSZkJ/)를 참조하십시오. – bmleite
좋은 질문을 계속하십시오. – Stewie
[그 예] (http://jsfiddle.net/bmleite/GSZkJ/)는 약간 오도하는 것입니다. 언뜻보기에 그것은 컨트롤러 인스턴스의 'num'속성을 공유하는 것처럼 보입니다. 실제로 일어나는 유일한 일은 내부 지시어가 내부 지시어와 외부 지시어가 모두 존재하는 scope 객체로 외부 지시어 컨트롤러 인스턴스의 increment 함수를 복사하는 것이다. 그것이 템플릿에서 호출 될 때 this == scope 객체. 이 포인트를 설명하려고하는이 [비틀어 진 예제] (http://jsfiddle.net/fess/a68Ra/)를 참조하십시오. –