AngularJS指令之间的通信 [英] AngularJS communication between directives

查看:98
本文介绍了AngularJS指令之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我'新Angular.js,我需要为我的应用程序指令之间一些沟通,我读到一些链接文件和要求,但无法理解它究竟是如何工作的。

对于一个简单的例子,我有:现场小提琴: http://jsfiddle.net/yw235n98/5/


  • 2指令:firstDir,secondDir ::一些数据

  • firstDir有一个点击的功能,这将改变数据值

  • 当firsDir点击功能被触发我想在secondDir修改数据了。

HTML:

 <机身NG-应用=对myApp>
首先指令:
<第一-DIR>
    < H3> {{firstCtrl.data}}< / H3 GT&;
    <按钮NG点击=firstCtrl.set(新价值')>改变数值和LT; /按钮>
< /第一DIR>
第二个指令:
<第二-DIR>
    < H3> {{secondCtrl.data}}< / H3 GT&;
< /秒-DIR>

的Javascript:

 (函数(){
    VAR应用= angular.module('对myApp',[]);    app.directive(firstDir功能(){
        返回{
            限制:'E',
            控制器:功能(){
                this.data ='初值';
                this.set =功能(值){
                    this.data =价值;
                    //使用第二个指令沟通?
                }
            },
            controllerAs:firstCtrl
        };
    });    app.directive(secondDir功能(){
        返回{
            限制:'E',
            控制器:功能(){
                this.data ='初值';
            },
            controllerAs:secondCtrl
        };
    });
})();


解决方案

您可以使用所谓三项赛他们之间沟通的一种方式。

一个指令可以发出上然后可以通过谁愿意向任何人被倾听的rootscope的事件。你可以使用 $ rootScope。$发出 $ rootScope。$广播来发布事件与数据,并使用 $范围。$关于听的事件。你的情况,你可以只是做 $范围。$发出为好。

  app.directive(firstDir功能(){
    返回{
        限制:'E',
        控制器:函数($范围){
            this.data ='初值';            this.set =功能(值){
             //放出用数据事件
              。$ $范围内发射出('FIRST_DIR_UPDATED',值);
                this.data =价值;
                //使用第二个指令沟通?
            }
        },
        controllerAs:firstCtrl
    };
});app.directive(secondDir功能(){
    返回{
        限制:'E',
        控制器:函数($范围){
          VAR _that =这一点;
          //监听到事件
          $范围。在$('FIRST_DIR_UPDATED',函数(即数据){
                 _that.data =数据;
          });
          this.data ='初值';
        },
        controllerAs:secondCtrl
    };
});

演示
DEMO2

____________________________________________________________________________

现在说到这,有时候真的是需要注入 $ rootScope 刚刚启用了在应用程序中的另一个节点三项赛。而是可以有一个发布/订阅机制,易于嵌入您的应用程序,并利用原型继承。

下面我加入2种方法发布订阅 $ rootScope的应用程序初始化过程中的原型。因此,任何儿童范围或隔离范围,将这些方法可用,沟通会很容易,而不用担心是否使用 $发出 $广播,我是否需要注入 $ rootscope 从孤立的通信范围的指令等。

  app.service('PubSubService',函数(){
   返回{初始化:初始化};     函数初始化(范围){
        //保留字典存储事件和其订阅
        变种publishEventMap = {};         //注册事件发布
          scope.constructor.prototype.publish = scope.constructor.prototype.publish
           ||功能(){
                VAR _thisScope =这一点,
                    处理程序,
                    ARGS,
                    EVNT;
                //获取数据的事件和休息
                ARGS = [] .slice.call(参数);
                EVNT = args.splice(0,1);
                //循环虽然每个handlerMap并调用处理程序
                angular.forEach((publishEventMap [EVNT] || []),功能(handlerMap){
                    handlerMap.handler.apply(_thisScope,参数);
                })
            }         //注册订阅事件
         scope.constructor.prototype.subscribe = scope.constructor.prototype.subscribe
            ||功能(EVNT,处理){
                VAR _thisScope =这一点,
                    处理器=(publishEventMap [EVNT] = publishEventMap [EVNT] || []);                //只要保持供参考scopeid后进行清理
                handlers.push({$ ID:_thisScope $ ID,处理程序:处理程序});
              //当范围摧毁删除它已订阅的处理程序。
             _thisScope。在$('$破坏',函数(){
                对于(VAR I = 0,1 = handlers.length; I<升;我++){
                  如果(处理器[1]。$ ID === _thisScope。的$ id){
                        handlers.splice(I,1);
                        打破;
                    }
                }
            });
        }    }
})。运行(函数($ rootScope,PubSubService){
    PubSubService.Initialize($ rootScope);
});

,你可以只是从您的应用程序的任何地方,而无需rootScope发布事件。

  $ scope.publish('eventName的',数据);

和应用程序的任何地方听,无需担心使用 $ rootScope $发出 $广播: -

  $ scope.subscribe('eventName的'功能(数据){
    //财产以后做
});

演示 - PubSub的

I'am new to Angular.js, I need for my application some communication between directives, I read some documentation about link and require, but can't understand exactly how it works.

For a simple example I have : live fiddle : http://jsfiddle.net/yw235n98/5/

  • 2 directives : firstDir, secondDir :: with some data
  • firstDir have a click function that will change the data value
  • when firsDir click function is triggered I want to change data in secondDir too.

HTML :

<body ng-app="myApp">
First Directive :   
<first-dir >
    <h3>{{firstCtrl.data}}</h3>
    <button ng-click="firstCtrl.set('NEW VALUE')">Change Value</button>
</first-dir>
Second Directive : 
<second-dir>
    <h3>{{secondCtrl.data}}</h3>
</second-dir>

Javascript :

(function(){
    var app = angular.module('myApp', []);

    app.directive("firstDir", function(){
        return {
            restrict : 'E',
            controller : function(){        
                this.data = 'init value';
                this.set = function(value){
                    this.data = value;
                    // communication with second Directive ???
                }       
            },
            controllerAs : 'firstCtrl'
        };  
    });

    app.directive("secondDir", function(){
        return {
            restrict : 'E',
            controller : function(){        
                this.data = 'init value';   
            },
            controllerAs : 'secondCtrl'
        };  
    });
})();

解决方案

One way you can communicate between them using what is called eventing.

One directive can emit an event on the rootscope which can then be listened by anybody who wants to. You could use $rootScope.$emit or $rootScope.$broadcast to publish events with data and use $scope.$on to listen to the event. In your case you could just do $scope.$emit as well.

app.directive("firstDir", function(){
    return {
        restrict : 'E',
        controller : function($scope){        
            this.data = 'init value';

            this.set = function(value){
             //EMIT THE EVENT WITH DATA
              $scope.$emit('FIRST_DIR_UPDATED', value);
                this.data = value;
                // communication with second Directive ???
            }       
        },
        controllerAs : 'firstCtrl'
    };  
});

app.directive("secondDir", function(){
    return {
        restrict : 'E',
        controller : function($scope){    
          var _that = this;
          //LISTEN TO THE EVENT 
          $scope.$on('FIRST_DIR_UPDATED', function(e, data){
                 _that.data = data;
          });
          this.data = 'init value';   
        },
        controllerAs : 'secondCtrl'
    };  
});

Demo Demo2

____________________________________________________________________________

Now speaking of which, it sometimes is really required to inject $rootScope just to have the eventing enabled to a different node in your application. You can instead have a pub/sub mechanism easily built in your app and make use of prototypical inheritance.

Here i am adding 2 methods publish and subscribe on $rootScope's prototype during app initialization. So any child scope or isolated scope will have these methods available and communication will be so easier without worrying about whether to use $emit, $broadcast, whether i need to inject a $rootscope for communication from isolated scoped directive etc.

app.service('PubSubService', function () {


   return {Initialize:Initialize};

     function Initialize (scope) {
        //Keep a dictionary to store the events and its subscriptions
        var publishEventMap = {};

         //Register publish events
          scope.constructor.prototype.publish =  scope.constructor.prototype.publish 
           || function () {
                var _thisScope = this,
                    handlers, 
                    args, 
                    evnt;
                //Get event and rest of the data
                args = [].slice.call(arguments);
                evnt = args.splice(0, 1);
                //Loop though each handlerMap and invoke the handler
                angular.forEach((publishEventMap[evnt] || []), function (handlerMap) {
                    handlerMap.handler.apply(_thisScope, args);
                })
            }

         //Register Subscribe events
         scope.constructor.prototype.subscribe = scope.constructor.prototype.subscribe 
            || function (evnt, handler) {
                var _thisScope = this,
                    handlers = (publishEventMap[evnt] = publishEventMap[evnt] || []);

                //Just keep the scopeid for reference later for cleanup
                handlers.push({ $id: _thisScope.$id, handler: handler });
              //When scope is destroy remove the handlers that it has subscribed.  
             _thisScope.$on('$destroy', function () {
                for(var i=0,l=handlers.length; i<l; i++){
                  if (handlers[i].$id === _thisScope.$id) {
                        handlers.splice(i, 1);
                        break;
                    }
                }
            });
        }

    }
}).run(function ($rootScope, PubSubService) {
    PubSubService.Initialize($rootScope);
});

and you could just have any place from your app publish an event without requiring a rootScope.

$scope.publish('eventName', data);

and listen anywhere on the application without worrying about using $rootScope or $emit or $broadcast:-

$scope.subscribe('eventName', function(data){
    //do somthing
});

Demo - PubSub

这篇关于AngularJS指令之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆