本文翻譯自:What's the correct way to communicate between controllers in AngularJS?
What's the correct way to communicate between controllers? 控制器之間通信的正確方法是什麼?
I'm currently using a horrible fudge involving window
: 我目前正在使用涉及window
的可怕軟糖:
function StockSubgroupCtrl($scope, $http) {
$scope.subgroups = [];
$scope.handleSubgroupsLoaded = function(data, status) {
$scope.subgroups = data;
}
$scope.fetch = function(prod_grp) {
$http.get('/api/stock/groups/' + prod_grp + '/subgroups/').success($scope.handleSubgroupsLoaded);
}
window.fetchStockSubgroups = $scope.fetch;
}
function StockGroupCtrl($scope, $http) {
...
$scope.select = function(prod_grp) {
$scope.selectedGroup = prod_grp;
window.fetchStockSubgroups(prod_grp);
}
}
#1樓
參考:https://stackoom.com/question/lDMS/AngularJS中控制器之間通信的正確方法是什麼
#2樓
Using $rootScope.$broadcast and $scope.$on for a PubSub communication. 使用$ rootScope。$ broadcast和$ scope。$ on進行PubSub通信。
Also, see this post: AngularJS – Communicating Between Controllers 另請參閱此文章: AngularJS - 在控制器之間進行通信
#3樓
GridLinked posted a PubSub solution which seems to be designed pretty well. GridLinked發佈了一個PubSub解決方案,似乎設計得非常好。 The service can be found, here . 這裏可以找到服務。
Also a diagram of their service: 還有他們的服務圖:
#4樓
Actually using emit and broadcast is inefficient because the event bubbles up and down the scope hierarchy which can easily degrade into performance bottlement for a complex application. 實際上使用發射和廣播是低效的,因爲事件在範圍層次結構中上下波動,這很容易降級爲複雜應用程序的性能瓶裝。
I would suggest to use a service. 我建議使用服務。 Here is how I recently implemented it in one of my projects - https://gist.github.com/3384419 . 以下是我最近在我的一個項目中實現它的方法 - https://gist.github.com/3384419 。
Basic idea - register a pubsub/event bus as a service. 基本思路 - 將pubsub / event bus註冊爲服務。 Then inject that eventbus where ever you need to subscribe or publish events/topics. 然後在需要訂閱或發佈事件/主題的地方注入eventbus。
#5樓
Regarding the original code - it appears you want to share data between scopes. 關於原始代碼 - 您似乎希望在範圍之間共享數據。 To share either Data or State between $scope the docs suggest using a service: 要在$ scope範圍內共享數據或狀態,文檔建議使用服務:
- To run stateless or stateful code shared across controllers — Use angular services instead. 運行跨控制器共享的無狀態或有狀態代碼 - 改爲使用角度服務。
- To instantiate or manage the life-cycle of other components (for example, to create service instances). 實例化或管理其他組件的生命週期(例如,創建服務實例)。
Ref: Angular Docs link here 參考:Angular Docs鏈接在這裏
#6樓
Here's the quick and dirty way. 這是快速而骯髒的方式。
// Add $injector as a parameter for your controller
function myAngularController($scope,$injector){
$scope.sendorders = function(){
// now you can use $injector to get the
// handle of $rootScope and broadcast to all
$injector.get('$rootScope').$broadcast('sinkallships');
};
}
Here is an example function to add within any of the sibling controllers: 這是一個在任何兄弟控制器中添加的示例函數:
$scope.$on('sinkallships', function() {
alert('Sink that ship!');
});
and of course here's your HTML: 當然這是你的HTML:
<button ngclick="sendorders()">Sink Enemy Ships</button>