Angularjs扩展指令控制器

时间:2013-11-14 20:18:32

标签: angularjs

我试图通过传递控制器来扩展指令。我可以通过require获取父指令的控制器,但我也想在扩展控制器上定义一个控制器。

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

2 个答案:

答案 0 :(得分:1)

您可以使用$ scope变量,两个控制器都可以访问该

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

答案 1 :(得分:1)

require可以获取一个数组,链接函数中的第四个arg也会变成一个数组,其中所请求的控制器的顺序与require数组中指定的顺序相同

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