2
我有我想在不同應用程序中的兄弟控制器之間進行通信的場景。所以我創建了示例demo,它使用發佈者訂戶服務來廣播和監聽事件。但訂閱該事件的代碼位於控制器中。所以我想了解這是否是最佳做法?什麼是實現這一目標的替代方法,舉例說明?
我指出以下情形 -
controllerA廣播事件和controllerB和controllerC聽它(1-多)
var app = angular.module('app', []);
app.controller('controllerA', ['$scope', 'pubsubService', controllerA]);
function controllerA($scope, pubsubService) {
$scope.teamName = '';
$scope.changeTeam = function() {
pubsubService.Publish("changeNameEvent", {
filterTeam: $scope.teamName
});
};
}
app.controller('controllerB', ['$scope', 'pubsubService', controllerB]);
function controllerB($scope, pubsubService) {
var callbackNameChanged = function(message) {
$scope.team = message.filterTeam
};
pubsubService.Subscribe("changeNameEvent", $scope, callbackNameChanged);
}
app.controller('controllerC', ['$scope', 'pubsubService', controllerC]);
function controllerC($scope, pubsubService) {
var callbackNameChanged = function(message) {
$scope.team = message.filterTeam
};
pubsubService.Subscribe("changeNameEvent", $scope, callbackNameChanged);
}
app.factory("pubsubService", ["$rootScope", function($rootScope) {
var Publish = function(message, item) {
try {
$rootScope.$broadcast(message, {
item: item
})
} catch (e) {
console.log(e.message)
}
};
var Subscribe = function(message, $scope, handler) {
try {
$scope.$on(message, function(event, args) {
handler(args.item)
})
} catch (e) {
console.log(e.message)
}
};
return {
Publish: Publish,
Subscribe: Subscribe
}
}]);
HTML代碼:
<body class='container'>
<div ng-controller="controllerA">
<input data-ng-model="teamName" type="text" data-ng-change="changeTeam()" />
</div>
<div ng-controller="controllerB">controllerB - You typed: {{team}}
<br />
</div>
<div ng-controller="controllerC">controllerC - You typed:{{team}}</div>
</body>