微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 使用发布/订阅的指令之间的Angularjs事件通信

我想用角度事件系统创建一个发布/订阅机制.
angular.module("app",[]);

angular.module("app").directive("first",function($rootScope){
        return {
          template: "First Directive",link:function(scope,element,attribute){
               $rootScope.$broadcast("OnFirstDirectiveCreated",{
                "message": "I'm first directive"
            });
      }
    }
})

angular.module("app").directive("second",function($rootScope){
        return {
          template: "Second Directive",attribute){
            var handler = $rootScope.$on("OnFirstDirectiveCreated",function (event,args) {
                  console.log("First Directive Message: " + args.message);
            });
      }
    }
})

如果我设置这样的HTML文档,控制台中不会显示任何消息:

<div ng-app="app">
  <first></first>
  <second></second>
</div>

如果我更改订单第一和第二,消息wirite在控制台.

<div ng-app="app">
  <second></second>
  <first></first>
</div>

但是我需要第一个指令或内部指令.

<div ng-app="app">
  <first></first>
  <second></second>
</div>

<div ng-app="app">
  <first>
      <second></second>
  </first>
</div>

我尝试过$rootScope.$broadcast和$rootScope.$emit,但没有下咽.

Working DEMO

解决方法

这是绝对正确的角度行为.

在第一个例子中:

<first></first>
<second></second>

Angular为第一个标签创建一个指令,并立即发送事件,但第二个指令尚未创建.

在第二个例子中:

<first></first>
<second></second>

在这里,您首先订阅一个事件,之后第一个指令发送消息.因此,第二个指令接受一个事件.

第三个例子:

<first>
   <second></second>
</first>

这种情况,以及第一个例子将不会奏效.

解:
一个解决方案是在第一个指令中设置超时,以便在创建后不立即发送事件.如果第二个参数为$timeout,则不提供延迟,则认行为是在DOM完成渲染后执行函数

angular.module("app").directive("first",function($rootScope,$timeout) {
  return {
    template: "First Directive",link: function(scope,attribute) {
      $timeout(function() {
        $rootScope.$broadcast("OnFirstDirectiveCreated",{
          "message": "I'm first directive"
        })
      });
    }
  }
});

Demo

原文地址:https://www.jb51.cc/js/155217.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐