【发布时间】:2014-05-19 08:54:14
【问题描述】:
我正在尝试在父指令与其嵌套的子指令之间进行通信,反之亦然。我已经设法通过使用 $broadcast 和 $emit 来实现这一点,但是因为我将一些参数传递给指令,所以我必须在我的指令上创建隔离范围,所以为了让 $broadcast/$emit工作我必须在父范围(scope.$parent.$broadcast)上广播“上一级”。 现在广播不再只是去嵌套的孩子,而是去同一级别的所有指令,这是我不想要的。我创建了一个 plunker 来显示这个问题,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');
});
}
}
});
【问题讨论】:
-
谢谢,但我认为这些都不适用;我不想注入服务(似乎矫枉过正)。要求父指令不起作用(我假设是因为使用了 transclude),并且在父作用域中执行表达式(通过 &)会起作用,但只有一种方式(嵌套指令在父指令上执行函数)。
-
您是否考虑为指令设置 id,然后只有与外部指令具有相同 id 的内部指令才能处理事件。看看这个例子plnkr.co/edit/dqGPDMF3f8NLBH4GX6dO?p=preview
-
是的,这实际上是我当前的实现/解决方法,正在使用您在 plunker 中显示的“id”。它有效,但感觉不...'正确'!如果有更清洁的方法,我只是在徘徊,但至少这是一个可行的选择!
标签: angularjs angularjs-directive angularjs-scope