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.
The problem you have is that sayHi
is a function that is never fired so myVar
is never set.
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) {}
Then you could do a ctrl.sayHi()
(But again, those params of sayHi
belongs to the controller function.)
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']
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.
Here is a little example: http://plnkr.co/edit/JXahWE43H3biouygmnOX?p=preview
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…