gpt4 book ai didi

javascript - 使用 AngularJS 发布订阅服务

转载 作者:行者123 更新时间:2023-11-29 14:42:44 24 4
gpt4 key购买 nike

我正在使用这段代码创建一个工厂,用于在 Controller 、指令和服务之间发布和订阅消息。

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 ,我该如何执行?

最佳答案

如果我理解正确的话,您希望将值 4 发布到 'notifying-service-event' 并且您希望在订阅者内部使用该值。

为了发布一个值,您需要将它传递给您的 emit 函数。

publish: function(msg) {
$rootScope.$emit('notifying-service-event', msg);
}

然后,当您使用此发布功能时,传递您想要的值。

node.on("click", click);

function click() {
NotifyingService.publish(4);
}

在处理 subscribe 事件时:

NotifyingService.subscribe($scope, function somethingChanged(event,msg) {
console.log(msg); //4
scope.number = msg //or whatever you want
scope.$apply();
});

您可以在此处找到完整示例:https://plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview

这是对问题的回答: Display informations about a bubble chart D3.js in AngularJS

关于javascript - 使用 AngularJS 发布订阅服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36628845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com