AngularJS - $emit 仅在其当前范围内有效? [英] AngularJS - $emit only works within it's current scope?
问题描述
我创建了 2 个指令:Parent 和 Child.试图让他们互相交谈.似乎如果他们都有一个范围,他们就不会收到事件.根据 $emit
所述的文档,这似乎不正确:通过作用域层次结构向上调度事件名称,通知注册的 ng.$rootScope.Scope#methods_$on 侦听器.代码>
那么肯定应该在范围内冒泡吗?
您可以创建子指令作为父指令的模板,因为模板指令确实获得了上述指令的范围.
.directive('parent', function ($timeout) {返回 {模板:'<child name="Jimmy"></child>',
<小时>
你真的需要事件总线吗?
另一种解决方案是在父指令上创建一个控制器并在子指令中要求它.
.directive('parent', function ($timeout) {返回 {控制器:函数(){this.hungry = 函数(消息){//某物}}
子指令:
.directive('child', function ($timeout) {返回 {要求:^父母",链接:函数(范围、元素、属性、父控件){parentCtrl.hungry("我饿了!")
I've created 2 directives: Parent and Child. Trying to get them to talk to one another. It seems if they both have a scope they don't receive the events. This doesn't seem correct according to the documentation which $emit
states: Dispatches an event name upwards through the scope hierarchy notifying the registered ng.$rootScope.Scope#methods_$on listeners.
So surely that should bubble up through scopes?
http://plnkr.co/edit/WNqN4XZKaLAvBEtSyERA?p=preview
The problem is with you parent/child assumption:
- Parent is only a parent element of Child but not a parent scope.
- Actually they are sibling scopes, both children of the $rootScope ($id: 002) in this case.
Why??
- Due to this commit,
Isolate scope is now available only to the isolate directive that requested it and its template
. - It means that parent directive contents (which included the child directive) are still linked to the outer scope.
- So the child directive creates isolated scope which is a child of the outer scope.
- Neither $emit nor $broadcast would work with sibling scopes.
Solution:
here is a plunker: http://plnkr.co/edit/EfKJthkQLitWnF2srykM?p=preview
You can create the child directive as a template of the parent directive, because template directives do get the directive's scope as mentioned above.
.directive('parent', function ($timeout) {
return {
template:'<child name="Jimmy"></child>',
do you really need the event bus?
Another solution would be to create a controller on the parent directive and to require it in child directives.
.directive('parent', function ($timeout) {
return {
controller: function(){
this.hungry = function(message){
// something
}
}
child directive:
.directive('child', function ($timeout) {
return {
require: "^parent",
link: function (scope, element, attrs, parentCtrl) {
parentCtrl.hungry("I'm hungry!")
这篇关于AngularJS - $emit 仅在其当前范围内有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!