在同一指令的链接函数中使用指令控制器的函数 [英] Using functions from directive controller within link function of same directive
问题描述
也许我对指令控制器的工作方式有一个根本的误解,据我所知,它们被用作一种暴露给其他指令的 API &控制器.我正在尝试让控制器和链接功能在内部进行通信.
Perhaps I have a fundamental misunderstanding of how directive controllers work, from what I understand they are used as a sort of API to be exposed to other directives & controllers. I am trying to get the controller and link function to communicate internally.
例如,我希望能够通过控制器函数设置一个变量,然后在链接函数中使用它:
For example I would like to be able to set a variable via the controller function and then use it in the link function:
var app = angular.module('test-app', []);
app.directive('coolDirective', function () {
return {
controller: function () {
this.sayHi = function($scope, $element, $attrs) {
$scope.myVar = "yo"
}
},
link: function(scope, el, attrs) {
console.log(scope.myVar);
}
}
});
如何在链接函数中访问 myVar 或 sayHi?还是我完全没有抓住重点?
How can I access myVar or sayHi within the link function? Or have I just missed the point completely?
推荐答案
控制器的 $scope(在控制器中定义,不在 sayHi
函数中)和链接 scope
是相同的.在控制器中设置一些东西将可以通过链接使用,反之亦然.
Both controller's $scope (defined in the controller, not in the sayHi
function) and link scope
are the same. Setting something in the controller will be usable from the link or viceversa.
您遇到的问题是 sayHi
是一个永远不会被触发的函数,因此永远不会设置 myVar
.
The problem you have is that sayHi
is a function that is never fired so myVar
is never set.
由于 sayHi
不在范围内,您需要对控制器的引用并执行此操作,您可以添加第四个参数,如下所示:
Since sayHi
is not in the scope, you need a reference to the controller and to do it, you can add a fourth parameter like this:
link: function(scope, element, attr, ctrl) {}
然后你可以做一个ctrl.sayHi()
(但同样,sayHi
的那些参数属于控制器函数.)
Then you could do a ctrl.sayHi()
(But again, those params of sayHi
belongs to the controller function.)
如果你需要另一个控制器并且仍然想使用它自己的指令,那么你也需要它.所以如果这个 coolDirective
需要访问 notCoolAtAll
的控制器,你可以这样做:
If you ever need to require another controller and still wanting to use its own directive, then you will need to require it too. So if this coolDirective
needs to access to the controller of notCoolAtAll
you could do:
require: ['coolDirective', 'notCoolAtAll']
这样就可以了.link
函数将接收一个控制器数组作为第四个参数,在这种情况下,第一个元素是 coolDirective
ctrl,第二个元素是 notCoolAtAll代码>一.
That will do the trick. The link
function will receive then an array of controllers as the fourth param and in this case the first element will be coolDirective
ctrl and the second one the notCoolAtAll
one.
这是一个小例子:http://plnkr.co/edit/JXahWE43H3biouygmnOX?p=预览
这篇关于在同一指令的链接函数中使用指令控制器的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!