在同级指令之间共享数据

share data between sibling directives

本文关键字:共享 数据 之间 指令      更新时间:2023-09-26

目前,我面临一个与angularjs指令有关的问题。我想将出口对象从方向1发送到方向2。两个指令具有相同的控制器作用域。我尝试从方向1向控制器发射事件,从控制器向方向2广播该事件,并在方向2上收听该事件。但这是行不通的。

方向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';
            };
        }
    };

这里,在directional1中,scope.selectOutlet()将outlet Id设置为scope.order.entityId。我想将该行移动/设置为directional2保存函数。

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

});

任何帮助。

您可以使用工厂或服务。把那个工厂纳入你的指令。现在,当您尝试设置写入工厂的函数中的数据时`app.factory("共享",function(){var obj={};

obj.setData = function(){
// call this function from directive 1.
 }
 return obj;
})`

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

我会试着做一些小提琴或弹拨器。如果不清楚。

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

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