3

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?

Ghazanfar Khan
  • 3,648
  • 8
  • 44
  • 89

1 Answers1

2

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.

In order to publish a value you need to pass it to your emit function.

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:

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

which was an answer to the question: Display informations about a bubble chart D3.js in AngularJS

Community
  • 1
  • 1
eko
  • 39,722
  • 10
  • 72
  • 98