I want to use socket.io in AngularJS. I found the following factory:
app.factory(\'socket\', function ($rootScope) {
var socket = io.connect();
retur
I was having the exact same problem of duplicate events after a browser refresh. I was using a 'factory', but switched to use a 'service'. Here's my socket.io wrapper:
myApp.service('mysocketio',['$rootScope', function($rootScope)
{
var socket = io.connect();
return {
on: function(eventName, callback )
{
socket.on(eventName, function()
{
var args=arguments;
$rootScope.$apply(function()
{
callback.apply(socket,args);
});
});
},
emit: function(eventName,data,callback)
{
socket.emit(eventName,data,function()
{
var args=arguments;
$rootScope.$apply(function()
{
if(callback)
{
callback.apply(socket,args);
}
});
});
}
}
}]);
I use this service inside my controller and listen for events:
myApp.controller('myController', ['mysocketio', function(mysocketio)
{
mysocketio.on( 'myevent', function(msg)
{
console.log('received event: ' + msg );
}
}]);
Once I switched from using a factory to using a service, I don't receive duplicates after a browser refresh.