2013-02-21 3 views
2

저는 angularJS에서 시작하고 있으며, 지시문과 컨트롤러로 범위를 지정하는 데 약간의 문제가 있습니다.격리 된 범위가있는 지시문에서 컨트롤러에 액세스하십시오.

아래 링크 된 예에서 두 가지 지시어가 있습니다. 하나의 속성 지시문 (showMessage)과 하나의 요소 지시문 (parentDirective)이 있습니다.

http://jsfiddle.net/ejSxM/1/

I는 요소를 클릭 할 때, 컨트롤러의 기능을 발사되도록 행동으로 showMessage를 사용하려는. 이것은 정상적인 html 요소에서 잘 작동하지만, 내 parentDirective에 적용하면 은 컨트롤러가 아닌 parentDirective의 범위를 취합니다.

이 내용은 첨부 된 예에서 확인할 수 있습니다. "나 혼자 야."를 클릭하면 지시문에 컨트롤러의 범위가 있으므로 컨트롤러 범위의 showMessage 함수가 올바르게 호출됩니다. 그러나 "I 'm a directive"를 클릭하면 지시문이 이제 상위 지시문의 범위를 가지며 오류를 표시합니다.

상위 디렉티브에 격리 된 범위가있는 경우에도 중첩 된 디렉티브에서 컨트롤러 범위에 액세스 할 수있는 방법이 있습니까? 당신의 지침에 다음 <my-directive onsomeevent="functionInMyController()"></my-directive>

을 그리고 :

답변

4

이 같이 당신의 지시에 표현에 전달할 수

입니다
... 
scope: { 
    onevent: '&onsomeevent' 
}, 
link: function() { 
    element.bind('click',function() { 
     scope.onevent(); 
    }); 
} 
... 

당신이 실행할 수 있도록, 당신은 onsomeevent 인수에서 식을 결합 표현이 무엇인지 모른 채로 지시어 내에서 사용하십시오. 표현식은 부모 범위에서 실행되므로 functionInMyController을 부모 범위에 정의해야합니다. 링크 함수에서 변수를이 표현식으로 전달할 수 있습니다.이 표현식은 여기 (범위 섹션에 있음) directives의 예제를 찾을 수 있습니다.

+0

감사합니다. 이 다른 접근 방식은 내 요구 사항에 완벽하게 부합하며 이제 불필요한 동작 지시문을 제거 할 수 있습니다. 관심있는 사람이 있다면, 위의 방법을 사용하는 또 다른 jsfiddle입니다 : http://jsfiddle.net/HDEF7/3/ – Sam

1

지시어에 대한 컨트롤러를 설정할 수 있습니다. 당신의 도움에 대한

controller - Controller constructor function. The controller is instantiated 
before the pre-linking phase and it is shared with other directives if they 
request it by name (see require attribute). 
This allows the directives to communicate with each other and augment each other's 
behavior. The controller is injectable with the following locals: 
$scope - Current scope associated with the element 
$element - Current element 
$attrs - Current attributes obeject for the element 
$transclude - A transclude linking function pre-bound to the correct transclusion 
scope:  
function(cloneLinkingFn). 

http://docs.angularjs.org/guide/directive

관련 문제