我試圖使用angular的$ broadcast從工廠A調用到工廠B.這兩個工廠在單獨的模塊中定義..下面是試圖做到這一點的代碼。
angular.module('secondApp', [])
.service('B', function($rootScope, $scope) {
$rootScope.$on('test', function(event, data) {
console.log(event, data);
});
});
var app = angular.module('firstApp', ['secondApp']);
app.controller('MainCtrl', function($scope, A) {
$scope.test = function() {
A.test();
};
});
app.service('A', function($rootScope) {
this.test = function() {
$rootScope.$broadcast('test', 'Hello from service A!');
};
});
您不幸無法使用broadcast/on進行交叉模塊通信。他們只需運行整個範圍,直到$ rootScope,並且每個模塊都有自己獨特的$ rootScope。 – 2014-11-05 00:36:15
謝謝Zack Argle,你如何建議我應該去實現這種跨模塊通信? – user2893858 2014-11-05 09:53:11
我會嘗試一個pub-sub服務,也許[this](https://github.com/glepretre/angular-pubsub)可以給你一些想法;) – glepretre 2014-11-05 09:57:12