2015-04-02 116 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