I'm trying to broadcast a message from $rootScope
from a service which is triggered on a message from Socket.io.
The problem is that it seems that $broadcast
isn't fired is fired, but my $on
in my controller isn't triggered.
My code looks like:
factory("notifications", ["socket", "$rootScope", function(socket, $rootScope){
return {
socket.on("notification", function(data){
$rootScope.$broadcast(data.something);
}
}
})
And my controller:
controller('RandomCtrl', function($scope, $http, $location){
function do_something(){
}
$scope.$on("some message from socket io", do_something);
});
Where is the problem?
I'm trying to broadcast a message from $rootScope
from a service which is triggered on a message from Socket.io.
The problem is that it seems that $broadcast
isn't fired is fired, but my $on
in my controller isn't triggered.
My code looks like:
factory("notifications", ["socket", "$rootScope", function(socket, $rootScope){
return {
socket.on("notification", function(data){
$rootScope.$broadcast(data.something);
}
}
})
And my controller:
controller('RandomCtrl', function($scope, $http, $location){
function do_something(){
}
$scope.$on("some message from socket io", do_something);
});
Where is the problem?
Share asked Sep 9, 2013 at 9:55 alexandernstalexandernst 15.1k25 gold badges107 silver badges213 bronze badges 8- Does your code ever reach the broadcast line? If you console.log('something') before the broadcast, does that output? – Foo L Commented Sep 9, 2013 at 9:58
- @FooL Yes, excuse me, I already updated the question. – alexandernst Commented Sep 9, 2013 at 9:58
-
$broadcast
takes a name & args. Have you tried$rootScope.$broadcast('socket', data.something)
& then in the controller:$scope.$on('socket', do_something);
– Foo L Commented Sep 9, 2013 at 10:03 -
@FooL well, the
data.something
is actually a string, so I'm using it as the event name. And I thought the args aren't mandatory, but I just tried with{}
as args and I get the same result. – alexandernst Commented Sep 9, 2013 at 10:05 -
You are correct, the arguments are optional. AND sending an event on the
$rootScope
should cause the message on the derived scopes to receive it. – Brian Genisio Commented Sep 9, 2013 at 10:10
1 Answer
Reset to default 6This should work. Some things to consider (some are probably obvious, sorry):
Are you sure that
data.something
and "some message from socket io" are the exact same strings?Could this be a timing issue? Is it possible that the message is being sent before the controller is registering the
$on
handler?Is this controller inside of a directive with isolate scope? I'm not sure if isolate scopes derive from
$rootScope
.What happens when you inject
$rootScope
into your controller and try$rootScope.$on
instead? This shouldn't be necessary at all, but it might help in debugging your problem.