Question

How can I broadcast an object through an event?

Currently I am trying:

app.run ($rootScope) ->
    message = {type: 'channel', action: 'create', data: { name: "ssss", id: 0}}
    $rootScope.$broadcast('message', message)

angular.module('WebChat').controller 'ChannelController', ($scope) -> 
    $scope.$on 'message', (message) ->
        console.log message
        console.log 'hi'

But I am getting no output

Edit I got it working. It seems that the first parameter of the callback function is the scope. I had to change the controller to:

angular.module('WebChat').controller 'ChannelController', ($scope) -> 
    $scope.$on 'message', (scope, message) ->
        console.log message
        console.log 'hi'
Was it helpful?

Solution

You are getting no output in your case since you are broadcasting before a controller is ready to accept messages. The module's run method is executed very early in the application's life-cycle, before controller's scopes are ready to listen to messages.

Here is the jsFiddle that illustrates this, check the console to see that broadcast happens before a listener is ready: http://jsfiddle.net/vPq2P/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top