【发布时间】:2016-09-22 11:31:23
【问题描述】:
我有一个场景,我想在不同应用程序中的兄弟控制器之间进行通信。所以我创建了示例demo,它使用发布者-订阅者服务来广播和监听事件。但是订阅事件的代码在控制器中。所以我想了解这是否是最佳实践?实现相同的替代方法是什么,举个例子?
我指出了以下情况 –
controllerA 广播事件并且 controllerB 和 controllerC 监听它(1-Many)
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>
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope angularjs-service