访问指令控制器内部所需的控制器的正确方法是什么?
What is the correct way to access controller that was required inside directive controller?
我有一个指令 require
属性:
require: '^testBox'
现在我想在指令的控制器中获取 testBox 控制器。我应该怎么做?
我正在尝试这样做:
controller: function(){
this.testBox.user
}
但看起来它不起作用。
我很清楚如何在 link
函数中获取所需的控制器。但是有没有办法在不使用 link
的情况下将其放入控制器中?
这仍然是一个open issue. So at the moment you can not just inject the required controller into your directive controller. I have updated your Plunker。这肯定有点老套,但问题是;您不能在 pre
或 post
link 函数中将 TextBoxCtrl
暴露给 UserCtrl
,因为控制器首先执行。所以我的想法是使用 watcher
来观察一个名为 textBox
的范围变量。定义值后,我在 UserCtrl
上声明一个变量并删除 watcher
。现在你可以像这样简单地在你的模板中使用它:
{{ user.textBox.name }}
这里是 link 函数的代码和 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();
}
});
}
但是,您也可以改用 link 函数。所需的控制器将作为第四个参数注入。
当您使用 controllerAs 时,它只是作为基础范围对象的 属性 添加(使用您定义的名称)。了解这一点后,您可以将父控制器实例附加为子控制器实例的 属性,如下所示:
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;
}
}
};
我有一个指令 require
属性:
require: '^testBox'
现在我想在指令的控制器中获取 testBox 控制器。我应该怎么做?
我正在尝试这样做:
controller: function(){
this.testBox.user
}
但看起来它不起作用。
我很清楚如何在 link
函数中获取所需的控制器。但是有没有办法在不使用 link
的情况下将其放入控制器中?
这仍然是一个open issue. So at the moment you can not just inject the required controller into your directive controller. I have updated your Plunker。这肯定有点老套,但问题是;您不能在 pre
或 post
link 函数中将 TextBoxCtrl
暴露给 UserCtrl
,因为控制器首先执行。所以我的想法是使用 watcher
来观察一个名为 textBox
的范围变量。定义值后,我在 UserCtrl
上声明一个变量并删除 watcher
。现在你可以像这样简单地在你的模板中使用它:
{{ user.textBox.name }}
这里是 link 函数的代码和 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();
}
});
}
但是,您也可以改用 link 函数。所需的控制器将作为第四个参数注入。
当您使用 controllerAs 时,它只是作为基础范围对象的 属性 添加(使用您定义的名称)。了解这一点后,您可以将父控制器实例附加为子控制器实例的 属性,如下所示:
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;
}
}
};