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