[英]Publish Subscribe service using AngularJS
I am using this code to create a factory for publishing and subscribing messages between controllers , directives and services . 我正在使用此代码创建一个工厂,用于在控制器,指令和服务之间发布和订阅消息。
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');
}
};
});
It is working fine but I want to pass data while I am publishing to someone whos subscribing that ,how do I do that. 它工作正常,但我想发布数据,而我发布给订阅它的人,我该怎么做。 Suppose I want to publish a value of 4 , How do I perform that?
假设我想发布值4,我该如何执行?
If I understood correctly you want to publish value 4
to the 'notifying-service-event'
and you want to use that value inside the subscriber. 如果我理解正确,您希望将值
4
发布到'notifying-service-event'
并且您希望在订阅者中使用该值。
In order to publish a value you need to pass it to your emit
function. 要发布值,您需要将其传递给
emit
函数。
publish: function(msg) {
$rootScope.$emit('notifying-service-event', msg);
}
Then, when you are using this publish function, pass the value you want. 然后,当您使用此发布功能时,传递您想要的值。
node.on("click", click);
function click() {
NotifyingService.publish(4);
}
While handling the subscribe
event: 在处理
subscribe
事件时:
NotifyingService.subscribe($scope, function somethingChanged(event,msg) {
console.log(msg); //4
scope.number = msg //or whatever you want
scope.$apply();
});
you can find a full example here: https://plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview 你可以在这里找到一个完整的例子: https : //plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview
which was an answer to the question: Display informations about a bubble chart D3.js in AngularJS 这是一个问题的答案: 显示有关AngularJS中气泡图D3.js的信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.