title: Improve this AngularJS factory to use with socket.io
body: <p>I want to use socket.io in AngularJS.
  I found the following factory:</p>
  
  <pre><code>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);
                      }
                  });
              })
          }
      };
  </code></pre>
  
  <p>and it is used in the controller like:</p>
  
  <pre><code>function MyCtrl($scope, socket) {
      socket.on('message', function(data) {
          ...
      });
  };
  </code></pre>
  
  <p>the problem is that each time the controller is visited another listener is added, so when a message is received it is handled multiple times.</p>
  
  <p>what can be a better strategy to integrate socket.io with AngularJS ?</p>
  
  <p>EDIT: I know that I can return nothing in the factory and do the listening there, then use $rootScope.$broadcast and $scope.$on in the controllers, but it doesn't look like a good solution.</p>
  
  <p>EDIT2: added to the factory</p>
  
  <pre><code>init: function() {
              socket.removeAllListeners();
  }
  </code></pre>
  
  <p>and call it at the beginning of each controller that use socket.io.</p>
  
  <p>still doesn't feel like the best solution.</p>