AngularJS - $ emit只能在它的当前范围内工作吗?

Int*_*lix 4 javascript angularjs

我创建了2个指令:Parent和Child.试图让他们互相交谈.看起来如果他们都有范围他们没有收到事件.根据文件说明这似乎不正确$emit:Dispatches an event name upwards through the scope hierarchy notifying the registered ng.$rootScope.Scope#methods_$on listeners.

那么肯定应该通过范围冒泡?

http://plnkr.co/edit/WNqN4XZKaLAvBEtSyERA?p=preview

Ila*_*mer 6

问题是你父母/孩子的假设:

  • Parent只是Child的父元素,而不是父范围.
  • 实际上它们是兄弟范围,在这种情况下是$ rootScope($ id:002)的两个子节点.

为什么??

  • 由于这个提交,Isolate scope is now available only to the isolate directive that requested it and its template.
  • 这意味着父指令内容(包括子指令)仍然链接到外部作用域.
  • 因此,child指令创建了隔离范围,它是外部范围的子代.
  • $ emit$ broadcast都不适用于兄弟范围.

在此输入图像描述


解:

这里有一个plunker:http://plnkr.co/edit/EfKJthkQLitWnF2srykM?p=preview

您可以将子指令创建为父指令的模板,因为模板指令确实获得了如上所述的指令范围.

.directive('parent', function ($timeout) {
  return {
    template:'<child name="Jimmy"></child>',
Run Code Online (Sandbox Code Playgroud)

你真的需要活动巴士吗?

另一种解决方案是在父指令上创建一个控制器,并在子指令中要求它.

.directive('parent', function ($timeout) {
  return {
    controller: function(){
      this.hungry = function(message){
        // something
      }
    }
Run Code Online (Sandbox Code Playgroud)

儿童指令:

.directive('child', function ($timeout) {
  return {
    require: "^parent",
    link: function (scope, element, attrs, parentCtrl) {

       parentCtrl.hungry("I'm hungry!")
Run Code Online (Sandbox Code Playgroud)