Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I broadcast an object in Angularjs?

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'
like image 466
user1703761 Avatar asked Sep 30 '12 15:09

user1703761


1 Answers

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/

like image 50
pkozlowski.opensource Avatar answered Oct 10 '22 02:10

pkozlowski.opensource