[英]communication between nested directives not working
我在指令栏中有指令Foo,我正在尝试在Foo中调用函数
但它不起作用。
http://jsfiddle.net/4d9Lfo95/3/
示例小提琴已创建。
angular.module('ui', []).directive('uiFoo',
function() {
return {
restrict: 'E',
template: '<p>Foo</p>',
link: function($scope, element, attrs) {
$scope.message = function() {
alert(1);
};
},
controller: function($scope) {
this.message = function() {
alert("Foo Function!");
}
}
};
}
).directive('uiBar',
function() {
return {
restrict: 'E',
template: '<button ng-click="callFunction()">Bar</button> <ui-foo></ui-foo>',
require: 'uiFoo',
scope: true,
link: function($scope, element, attrs, uiFooController) {
$scope.callFunction = function() {
alert('Bar Function');
uiFooController.message();
}
}
};
}
);angular.module('myApp', ['ui']);
UI看起来像这样
<div ng-app="myApp"> <ui-bar> </ui-bar></div>
您忽略了此错误消息:
找不到指令'uiBar'所需的控制器'uiFoo'!
问题是require层次结构在树上向上搜索,而不是在树上向下搜索。 因此, ui-bar
试图在其祖先之一而不是其子孙中找到一个uiFoo
指令控制器,或者在其自身上(带有^
符号)。
如果要从child指令调用方法,只需使用范围: http : //jsfiddle.net/4d9Lfo95/5/
angular.module('ui', []).directive('uiFoo',
function() {
return {
restrict: 'E',
template: '<p>Foo</p>',
controller: function($scope) {
$scope.message = function() {
alert("Foo Function!");
}
}
};
}
).directive('uiBar',
function() {
return {
restrict: 'E',
template: '<button ng-click="callFunction()">Bar</button> <ui-foo></ui-foo>',
scope: true,
controller: function($scope) {
$scope.callFunction = function() {
alert('Bar Function');
$scope.message();
}
}
};
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.