访问指令控制器内所需的控制器的正确方法是什么?

时间:2015-11-11 09:14:03

标签: angularjs angularjs-directive angularjs-scope angularjs-controller

我有require属性的指令:

require: '^testBox'

现在我想在我的指令的控制器中获取testBox控制器。我该怎么办?

我试图这样做:

controller: function(){
  this.testBox.user
}

但看起来不起作用。 我很清楚如何在link函数中获取所需的控制器。但有没有办法在不使用link的情况下将其置于控制器内?

Code on plunker

2 个答案:

答案 0 :(得分:2)

这仍然是 open issue 。所以目前你不能只将所需的控制器注入指令控制器。我已更新了您的Plunker。它肯定有点hacky但问题是;您无法在TextBoxCtrlUserCtrl链接功能中将pre公开给post,因为控制器会先执行。所以我的想法是使用watcher来观察名为textBox的范围变量。定义值后,我在UserCtrl上声明一个变量并删除watcher。现在您可以在模板中使用它,如下所示:

{{ user.textBox.name }}

以下是链接函数的代码和user指令的控制器:

link: function($scope, $element, $attrs, ctrl) {
  $scope.textBox = ctrl
},
controller: function($scope) {
  var vm = this;

  var watcher = $scope.$watch('textBox', function(newVal) {
    if(newVal) {
      vm.textBox = newVal;
      watcher();
    }
  });
}

但是,您也可以使用链接功能。所需的控制器将作为第四个参数注入。

答案 1 :(得分:0)

当您使用控制器时,它只是作为基础范围对象的属性添加(使用您已定义的名称)。知道了这一点,您可以将父控制器实例作为子控制器实例的属性附加,如下所示:

    function exampleDirective() {
        return {            
            require: '^testBox',
            link: function (scope, element, attrs, testBox) {
                scope.example.testBox = testBox;
            },
            controllerAs: 'example',
            controller: function() {
                // silly example, but you get the idea!
                this.user = this.testBox.user;
            }
        }
    };