2013-11-14 79 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

需要可以採取的陣列,在該鏈接功能第四ARG然後也變得與作爲需要數組中指定以相同的順序被請求的控制器的陣列

.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>