2015-04-02 104 views
0

我无法搞清楚如何有一个指令一个指令不同的内触发事件指令可与其他指令沟通

说我有以下2个指令

project.directive('ActionButton', function() { 
return { 
    restrict: 'E', 
    scope: { 
     orderId: '@' 
    }, 
    templateUrl: '/scripts/templates/directive-templates/order-action-button.html', 
    link: function (scope, element, attrs) { 
     scope.doAction = function() { 
      // I want to trigger 'scope.refreshOrderDetails' in my other directive from here 
     } 
    } 
} 

project.directive('OrderView', function() { 
return { 
    restrict: 'E', 
    scope: { 
     orderId: '@' 
    }, 
    templateUrl: '/scripts/templates/directive-templates/order-view.html', 
    link: function (scope, element, attrs) { 
     scope.refreshOrderDetails = function() { 
      // data is refreshed here 
     } 
    } 
} 

,而且我用我的指令,这样

<ca-action-button order-id="{{orderId}}"></ca-order-action-button> 

<ca-order-view order-id="{{orderId}}"></ca-order-details> 

其中CA-订单细节开始用数据填充,但是当CA阶动作按钮触发事件需要刷新。

动作按钮将被加载许多doAction(它是一个按钮下拉多动作),并且会有一些不同的OrderView类型指令,每个指令都有自己的一组数据需要刷新不同的触发器

+0

好像你需要使用一个父控制器为这两个指令通过,而不是使用事件(这可以得到笨拙,尤其是当你拥有多套指令的页面上) – Adam 2015-04-02 14:13:37

回答

2

您可以通过广播做到这一点,监听事件:

ca-order-action-button

$rootScope.$broadcast('event', { id: 12345 }); 

ca-order-details

$scope.$on('event', function (event, data) { console.log(data.id); }); 
+1

我建议CA沟通-order-details订阅其作用域上的事件而不是$ rootScope。这样,当范围被破坏时,偶数处理程序不会四处闲逛。 – 2015-04-02 14:13:49

+1

@JohnBledsoe yep。固定。 – paul 2015-04-02 14:16:27

+0

非常感谢你!这是完美的作品 – mrb398 2015-04-02 14:22:45

1

你会错误的。指令的链接函数只能用于执行DOM转换。我想使用控制器和$ rootScope进行事件。

project.directive('ActionButton', function() { 
    return { 
    restrict: 'E', 
    scope: { 
     orderId: '@' 
    }, 
    templateUrl: '/scripts/templates/directive-templates/order-action-button.html', 
    controller: 'ActionButtonCtrl' 
    }; 
}); 

project.directive('OrderView', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      orderId: '@' 
     }, 
     templateUrl: '/scripts/templates/directive-templates/order-view.html', 
     controller: 'OrderViewCtrl' 
    } 
}); 

project.controller('ActionButtonCtrl', 
['$scope', '$rootScope', function($scope, $rootScope) { 
    $scope.doAction = function() { 
    $rooScope.$emit('refreshOrder', $scope.orderId); 
    }; 
}]); 

project.controller('OrderViewCtrl', 
['$scope', '$rootScope', function($scope, $rootScope) { 
    var deregFn = $rootScope.$on('refreshOrder', function(orderId) { 
    // refresh order details here 
    }); 

    // Once scope is destroyed - cleanup 
    $scope.$on('$destroy', function() { 
    deregfn(); 
    }); 
}]); 
+0

它是有道理的,我已经更新这些指令,以利用控制器功能,而不是链接功能。谢谢你的提示! – mrb398 2015-04-02 14:47:12