tib*_*bus 25 javascript angularjs angularjs-directive
我是Angular.js的新手,我需要在我的应用程序之间进行指令之间的一些通信,我阅读了一些关于链接和需求的文档,但是无法准确理解它是如何工作的.
我有一个简单的例子:活小提琴:http://jsfiddle.net/yw235n98/5/
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'
        };  
    });
})();
PSL*_*PSL 38
使用所谓的事件可以在它们之间进行通信的一种方法.
一个指令可以在根镜上发出一个事件,然后任何想要的人都可以监听它.您可以使用$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'
    };  
});
____________________________________________________________________________
现在谈到它,有时真的需要注入$rootScope才能将事件启用到应用程序中的不同节点.您可以在应用程序中轻松构建pub/sub机制,并使用原型继承.
在这里,我将2种方法publish,并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
});
Max*_*tin 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;
            });
        }
    }
});
| 归档时间: | 
 | 
| 查看次数: | 21054 次 | 
| 最近记录: |