在兄弟指令之间共享数据

时间:2015-11-23 07:09:31

标签: javascript angularjs angularjs-directive angularjs-scope

目前,我正面临一个与angularjs指令相关的问题。我想将从outlet1的outlet对象发送到directive2。两个指令具有相同的控制器范围。我尝试从directive1向控制器发出事件,将该事件从控制器广播到directive2并在directive2上侦听该事件。但这不起作用。

指令1:

angular.module('moduleName')
.directive('directive1', function() {
    return {
        restrict: 'E',
        templateUrl: 'directive1.html',
        scope: false,
        link: function(scope) {
            scope.selectOutlet = function(outlet) {
                scope.order.entityId = outlet.id;
                scope.navigation.currentTab = 'right';
            };
        }
    };

这里,在directive1中,scope.selectOutlet()将outletId设置为scope.order.entityId。我想将该行移动/设置为directive2保存功能。

指令2:

angular.module('moduleName')
.directive('directive2', function(config, $rootScope, $state) {
    return {
        restrict: 'E',
        templateUrl: 'directive2.html',
        scope: false,
        link: function(scope) {
            scope.save = function() {
                // Save functionality  
                // scope.order.entityId = outlet.id; This is what i want to do
            };
        }
    };
});

});

任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用工厂或服务。将该工厂注入您的指令。现在,当您尝试将函数中的数据写入工厂时。 `app.factory( '共享',函数(){ var obj = {};

<input type="text" pattern="[1-9][0-9]{5}" />

因此,如果将此工厂包含在指令中,您将获得2个指令中的数据。

我会尝试制作一些jsfiddle或者plunker。如果不清楚。

答案 1 :(得分:0)

在第一个指令中执行以下操作

angular.module('moduleName')
  .directive('directive1', function($rootScope) {
   return {
    restrict: 'E',
    templateUrl: 'directive1.html',
    scope: false,
    link: function(scope) {
        scope.selectOutlet = function(outlet) {
             $rootScope.$broadcast('save:outlet',outlet);
            //scope.order.entityId = outlet.id;
            //scope.navigation.currentTab = 'right';
        };
    }
};

和第二次

angular.module('moduleName')
 .directive('directive2', function(config, $rootScope, $state) {
   return {
    restrict: 'E',
    templateUrl: 'directive2.html',
    scope: false,
    link: function(scope) {
       $rootScope.$on('save:outlet',function(event,data){
         // do staff here 
       });
    }
   };
 });
相关问题