2013-11-14 7 views
1

컨트롤러를 전달하여 지시문을 확장하려고합니다. require을 통해 상위 디렉티브 컨트롤러를 가져올 수 있지만 확장 컨트롤러에 컨트롤러를 정의하고 싶습니다.Angularjs 확장 지시문 컨트롤러

.directive('smelly', function(){ 
    return { 
    restrict: 'E', 
    controller: function(){ 
     this.doWork = function(){ alert('smelly work'); }; 
    }, 
    link: function($scope, $element, $attributes, controller){  
     $element.bind('click',function(){ 
     controller.doWork(); 
     }); 
    } 
    }; 
}) 
.directive('xtSmelly', function(){ 
    return {  
    controller: function(){ 
     this.name = "brian"; 
    }, 
    require: 'smelly', 
    link: function($scope, $element, $attributes, smellyController){ 
     smellyController.doWork = function(){ 
     alert('xt-smelly work by: ' + xtSmellyController.name); 
     }; 
    } 
    }; 
}) 

HTML 
<smelly xt-smelly>click me</smelly> 

어떻게하면 xtSmellyController.name에 액세스 할 수 있습니까?

답변

1

당신은 $ 범위 변수를 사용할 수 있습니다, 두 컨트롤러는

return {  
controller: function($scope){ 
    $scope.name = "brian"; 
}, 
require: 'smelly', 
link: function($scope, $element, $attributes, smellyController){ 
    smellyController.doWork = function(){ 
    alert('xt-smelly work by: ' + $scope.name); 
    }; 
} 

}에 액세스 할 수 있습니다;

: http://plnkr.co/edit/dYIr36lKtnybxvkUlOJ1?p=preview

+0

흠 , 그것은 작동하지만 올바른 방법입니까? 그것을 범위에 던져 우려의 분리를 파기하지 않습니까? – user2809175

1

배열을 취할 수있는 요구는 링크 기능의 네 번째 인수는 또한 반드시 필요한 배열에 지정된 것과 동일한 순서로 요청와의 배열된다

.directive('smelly', function(){ 
    return { 
    restrict: 'E', 
    controller: function(){ 
     this.doWork = function(){ alert('smelly work'); }; 
    }, 
    link: function($scope, $element, $attributes, controller){  
     $element.bind('click',function(){ 
     controller.doWork(); 
     }); 
    } 
    }; 
}) 
.directive('xtSmelly', function(){ 
    return {  
    controller: function(){ 
     this.name = "brian"; 
    }, 
    require: ['smelly', 'xtSmelly'], 
    link: function($scope, $element, $attributes, controllers){ 
     var smellyController = controllers[0]; 
     var xtSmellyController = controllers[1]; 
     smellyController.doWork = function(){ 
     alert('xt-smelly work by: ' + xtSmellyController.name); 
     }; 
    } 
    }; 
}) 

HTML 
<smelly xt-smelly>click me</smelly>