1

我试图通过传递控制器来扩展指令。我可以通过 获取父指令的控制器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?

4

2 回答 2

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>  
于 2014-06-26T16:31:00.483 回答
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

于 2013-11-14T20:42:56.783 回答