title: Node.js + AngularJS + socket.io: connect state and manually disconnect
body: <p>I use nodejs with socket.io and angularjs on client. I picked up angular-socketio example from the Internet and added <code>disconnect</code> method to It.</p>
  
  <p>Socket service:</p>
  
  <pre class="lang-js prettyprint-override"><code>angular.module('app')
    .factory('socket', ['$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);
              }
            });
          })
        },
        disconnect: function () {
          socket.disconnect();
        },
        socket: socket
      };
  
    }]);
  </code></pre>
  
  <p>Controller:</p>
  
  <pre class="lang-js prettyprint-override"><code>angular.module('app')
    .controller('Controller', ['$scope', 'socket', function ($scope, socket) {
  
      socket.emit('register')
  
      socket.on('connect', function () {
          console.log('Socket connected');
      });
  
      socket.on('disconnect', function () {
          console.log('Socket disconnected');
      });
  
      socket.on('register', function (reginfo) {
          console.log('Register: %s, cname=%s', reginfo.ok, reginfo.cname);
          socket.disconnect(); // &lt;-- this line throw Error
      });
  
      socket.on('last', updateSnapshot);
  
      socket.on('state', updateSnapshot);
  
      function updateSnapshot(snapshot) { ... }
  
  }]);
  </code></pre>
  
  <p>But when I try to disconnect use this method I catch Error:</p>
  
  <pre><code>Error: $apply already in progress
    at Error (&lt;anonymous&gt;)
    at beginPhase (http://localhost:4000/scripts/vendor/angular.js:8182:15)
    at Object.$get.Scope.$apply (http://localhost:4000/scripts/vendor/angular.js:7984:11)
    at SocketNamespace.on (http://localhost:4000/scripts/services/socket.js:10:32)
    at SocketNamespace.EventEmitter.emit [as $emit] (http://localhost:4000/socket.io/socket.io.js:633:15)
    at Socket.publish (http://localhost:4000/socket.io/socket.io.js:1593:19)
    at Socket.onDisconnect (http://localhost:4000/socket.io/socket.io.js:1970:14)
    at Socket.disconnect (http://localhost:4000/socket.io/socket.io.js:1836:12)
    at SocketNamespace.&lt;anonymous&gt; (http://localhost:4000/scripts/controllers/controller.js:38:34)
    at on (http://localhost:4000/scripts/services/socket.js:11:34)
  </code></pre>
  
  <p>And I don't understand where to dig…</p>