如果指令在指令定义对象集中没有require
属性,那么传递给link
的第4个参数就是该指令的控制器。
如果我们做设置require
,那么第4个属性是我们require
的控制器(或控制器数组),并且指令失去了对它自己的引用控制器。访问此内容的最佳方式是什么?
angular.module 'example', []
.directive 'directive1', ->
restrict: 'E'
controller: ($log)->
@sayHi = -> $log.info('hi')
link: (scope, element, attributes, controller)->
controller.sayHi() # works.
.directive 'directive2', ->
restrict: 'A'
require: 'directive1'
controller: ($log)->
@sayBye = -> $log.info('bye')
link: (scope, element, attributes, controller)->
controller.sayHi() # works
# how would I access sayBye?
我意识到我可以将sayBye
放在$scope
上,并通过链接功能中的scope
进行访问,但有没有办法做到这一点,不会&#39} ; 涉及范围?
这是唯一的方法吗?
.directive 'directive2', ->
ownCtrl = {}
restrict: 'A'
require: 'directive1'
controller: ($log)->
@sayBye = -> $log.info('bye')
ownCtrl = this
link: (scope, element, attributes, controller)->
controller.sayHi() # works
ownCtrl.sayBye()
答案 0 :(得分:4)
您可以要求一系列控制器,包括指令的控制器本身。正如$compile
documentation中提供的评论中提到的那样。
angular.module('demo', [])
.directive('directive1', function() {
return {
controller: function() {
this.sayHello = function(directiveName) {
console.log(directiveName + ' says hi');
};
},
link: function(scope, elem, attr, ctrl) {
ctrl.sayHello('directive1');
}
};
})
.directive('directive2', function() {
return {
require: ['^directive1', 'directive2'],
controller: function() {
this.sayGoodbye = function() {
console.log('goodbye');
};
},
link: function(scope, elem, attr, ctrls) {
var d1Ctrl = ctrls[0],
d2Ctrl = ctrls[1];
d1Ctrl.sayHello('directive2');
d2Ctrl.sayGoodbye();
}
};
});

<div ng-app="demo">
<div directive1>
<div directive2></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
&#13;