I want to use socket.io in AngularJS. I found the following factory:
app.factory('socket', 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); } }); }) } };
and it is used in the controller, for example:
function MyCtrl($scope, socket) { socket.on('message', function(data) { ... }); };
the problem is that every time the controller is visited, another listener is added, so when the message is received, it is processed several times.
What could be the best strategy for integrating socket.io with AngularJS?
EDIT: I know that I cannot return anything to the factory and listen there, and then use $ rootScope. $ broadcast and $ scope. $ on in controllers, but that doesn't seem like a good solution.
EDIT2: added to factory
init: function() { socket.removeAllListeners(); }
and call it at the beginning of each controller using socket.io.
still not like the best solution.
Gal Ben-Haim Jan 17 '13 at 22:10 2013-01-17 22:10
source share