【发布时间】:2016-04-14 16:28:28
【问题描述】:
我正在使用此代码创建一个工厂,用于在控制器、指令和服务之间发布和订阅消息。
angular.module('app', []);
angular.module('app').controller('TheCtrl', function($scope, NotifyingService) {
$scope.notifications = 0;
$scope.notify = function() {
NotifyingService.publish();
};
// ... stuff ...
NotifyingService.subscribe($scope, function somethingChanged() {
// Handle notification
$scope.notifications++;
});
});
angular.module('app').factory('NotifyingService', function($rootScope) {
return {
subscribe: function(scope, callback) {
var handler = $rootScope.$on('notifying-service-event', callback);
scope.$on('$destroy', handler);
},
publish: function() {
$rootScope.$emit('notifying-service-event');
}
};
});
它工作正常,但我想在发布给订阅它的人时传递数据,我该怎么做。 假设我想发布 4 的值,我该如何执行?
【问题讨论】:
标签: javascript angularjs publish-subscribe