指令之间的AngularJS通信

时间:2014-08-12 21:44:57

标签: javascript angularjs angularjs-directive

我是Angular.js的新手,我需要在我的应用程序之间进行指令之间的一些通信,我阅读了一些关于链接和要求的文档,但无法准确理解它是如何工作的。

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

  • 2个指令:firstDir,secondDir :: with some data
  • firstDir有一个可以更改数据值的点击功能
  • 当firsDir点击功能被触发时我也想更改secondDir中的数据。

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'
        };  
    });
})();

3 个答案:

答案 0 :(得分:38)

使用所谓的事件可以在他们之间进行通信的一种方式。

一个指令可以在rootcope上发出一个事件,然后任何想要的人都可以监听它。您可以使用$rootScope.$emit$rootScope.$broadcast发布包含数据的事件,并使用$scope.$on收听该事件。在您的情况下,您也可以$scope.$emit

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

<强> ____________________________________________________________________________

现在谈到它,有时真的需要注入$rootScope只是为了让应用程序中的另一个节点启用事件。您可以在应用程序中轻松构建pub / sub机制,并使用原型继承。

这里我在应用初始化期间在publish原型上添加了2个方法subscribe$rootScope's。因此,任何子范围或隔离范围都将提供这些方法,并且通信将变得如此简单,而不必担心是否使用$emit$broadcast,是否需要注入$rootscope来进行通信孤立的范围指令等。

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);
});

你可以在你的应用中找到任何地方发布一个事件而不需要rootScope。

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

并随时随地收听应用,无需担心使用$rootScope$emit$broadcast: -

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

<强> Demo - PubSub

答案 1 :(得分:17)

从您的示例中,指令结构不是父子。因此,您无法通过其控制器共享方法。我会用$rootScope.$broadcast。 (见DOCS

一个指令叫:

$rootScope.$broadcast('someEvent', [1,2,3]);

第二个指令侦听:

 scope.$on('someEvent', function(event, mass) {
    console.log(mass)}
  );

演示 Fiddle


固定指令:

app.directive("firstDir", function ($rootScope) {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            scope.dataToPass = 'empty';
            scope.doClick = function (valueToPass) {
                scope.dataToPass = valueToPass;
                $rootScope.$broadcast('someEvent', {
                    data: valueToPass
                });
            }
        }
    };
});

app.directive("secondDir", function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            scope.receivedData = 'none';

            scope.$on('someEvent', function (event, result) {
                scope.receivedData = result.data;
            });
        }
    }
});

答案 2 :(得分:-1)

我正在使用的是导出指令控制器。假设我有以下指令:

app.directive('mainDirective', function () {
  return {
    require: 'mainDirective'
    restrict: 'E',
    scope: {
      controller: '='
    },
    controller: [
      '$scope',
      function ($scope) {
        // controller methods
        this.doSomething = function () { ... },

        $scope.controller = this
        return this
      }
    ],
    link: function (scope, element, attrs, mainDirective) {
      // some linking stuff
    }
  }
});

我的HTML看起来像这样:

<main-directive controller="mainDirective"></main-directive>
<sub-directive main-directive="mainDirective"></sub-directive>

如果我想从子指令控制main-directive,我可以轻松地从它的范围中抓取它并做任何我想要的事情......

app.directive('subDirective', function () {
  return {
    restrict: 'E',
    scope: {
      mainDirective: '='
    }
    link: function (scope, element, attrs) {
      // do something with main directive
      scope.mainDirective.doSomething();
    }
  }
});