我试图在父指令和它的嵌套子指令之间进行通信,而另一种方式。我已经设法通过使用$ broadcast和$ emit来实现此目的,但是因为我将一些参数传递给了指令,所以我必须在指令上创建隔离范围,因此为了让$ broadcast/$ emit我必须在父范围(范围:$ parent。$ broadcast)上播出'上一级'。 现在广播不再只是去嵌套的孩子,而是去了同一级别的所有指令,这是我不想要的。我创建了一个潜水员来显示问题,here。 我需要的是当按下其中一个按钮时,只有子指令才能接收广播消息,反之亦然。我是否错过了某些东西,或者在使用隔离范围时不可行?嵌套指令之间的通信
在我的HTML:
<body ng-app="myApp">
<directive1 data-title="Click me to change name">
<directive2 data-name="John Smith"></directive2>
</directive1>
<directive1 data-title="Click me to change this other name">
<directive2 data-name="Gordon Freeman"></directive2>
</directive1>
</body>
指令1:
<div>
<button ng-click="changeName()">{{title}}</button>
<div ng-transclude></div>
</div>
指令2:
<div>
<h2>{{name}}</h2>
</div>
我的指令:
myApp.directive('directive1', function(){
return {
restrict: 'E',
replace: true,
templateUrl: 'Directive1.html',
transclude: true,
scope: {
title: '@'
},
link: function(scope, elem){
scope.changeName = function() {
scope.$parent.$broadcast('ChangeName');
};
scope.$parent.$on('NameChanged', function(event, args){
scope.title = 'Name changed to ' + args;
});
}
}
});
myApp.directive('directive2', function(){
return {
restrict: 'E',
replace: true,
templateUrl: 'Directive2.html',
scope: {
name: '@'
},
link: function(scope, elem){
scope.$on('ChangeName', function(event, args){
scope.name = 'Adam West';
scope.$emit('NameChanged', 'Adam West');
});
}
}
});
这里看看http://programmers.stackexchange.com/questions/223006/communication-between-nested-directives – user902383
谢谢,但我不认为任何的是适用于此处;我不想注入一个服务(似乎矫枉过正)。需要父指令不起作用(我假定是因为使用了transclude),并且在父范围中执行表达式(通过&)将会工作,但只有一种方法(父指令的嵌套指令执行函数)。 –
你有没有考虑设置id的指令,然后只有内部指令持有相同的id作为外部指令将处理事件。看看这个例子http://plnkr.co/edit/dqGPDMF3f8NLBH4GX6dO?p=preview – user902383