AngularJS - $发出只能在它的当前范围是什么? [英] AngularJS - $emit only works within it's current scope?
问题描述
我创建2指令:父母与子女。试图让他们彼此交谈。看来,如果它们都具有一个范围他们不接受的事件。这根据该 $发出
规定的文件似乎不正确的:通过范围层次向上将事件调度名通知注册纳克$ rootScope .Scope#$ methods_上的监听器。
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=$p$ PVIEW
推荐答案
- 父仅在儿童而非父作用域的父元素。
- 其实他们的同级范围后,两个孩子的 $ rootScope ( $ ID:002 的)。在这种情况下
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.
- 由于这次提交,
隔离范围目前只提供给请求它和它的模板
。 该分离指令 - 这意味着母公司指令内容(包括子指令)都依然与外部范围。
- 所以儿童指令创建孤立的范围是外范围的子项。
- 无论 $ EMIT 也没有 $广播将与同级范围工作。
- 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.
是一个plunker: http://plnkr.co/edit/EfKJthkQLitWnF2srykM? p = preVIEW
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
}
}
子指令:
.directive('child', function ($timeout) {
return {
require: "^parent",
link: function (scope, element, attrs, parentCtrl) {
parentCtrl.hungry("I'm hungry!")
这篇关于AngularJS - $发出只能在它的当前范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!