繁体   English   中英

指令之间的AngularJS通信

[英]AngularJS communication between directives

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

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

  • 2个指令:firstDir,secondDir ::带有一些数据
  • 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'
        };  
    });
})();

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

一个指令可以在根镜上发出一个事件,然后任何想要的人都可以监听它。 您可以使用$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'
    };  
});

演示 DEMO2

____________________________________________________________________________

现在谈到它,有时真的需要注入$rootScope才能将事件启用到应用程序中的不同节点。 您可以在应用程序中轻松构建pub / sub机制,并使用原型继承。

在这里,我在应用程序初始化期间在$rootScope's原型上添加了2个方法publishsubscribe 因此,任何子范围或隔离范围都将提供这些方法,并且通信将变得如此简单,而不必担心是否使用$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
});

演示 - PubSub

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

一条指令称:

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

第二个指令侦听:

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

演示小提琴


固定指令:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM