Skip to content

Instantly share code, notes, and snippets.

@pulkitsinghal
Last active October 21, 2016 20:20
Show Gist options
  • Save pulkitsinghal/f8ca556da0defd417e63d2cf5b875159 to your computer and use it in GitHub Desktop.
Save pulkitsinghal/f8ca556da0defd417e63d2cf5b875159 to your computer and use it in GitHub Desktop.
Wrap sockets for use with angular - part1
  1. Install a 3rd party utility to help with wrapping the socket library:
bower install angular-socket-io`
  1. Update index.html to provide a websocket implementation like socket.io and the wrapper utility:
<script src="//cdn.socket.io/socket.io-1.1.0.js"></script>
<script src="bower_components/angular-socket-io/socket.min.js"></script>
  1. Update app.js to use sockets:
angular.module('MyApp',[
  ...,
  'btford.socket-io'
])

/*global io: true */
.factory('$sockets', function (socketFactory) {
  // 1. initialize socket.io implementation with a URL and any other custom options
  var myIoSocket = io.connect('http://localhost:3001');
  // 2. wrap the socket implementation
  var mySocket = socketFactory({
    ioSocket: myIoSocket
  });
  // 3. optionally, forward events to the $rootScope if you wish
  mySocket.forward('error');
  // 4. finish setup
  return mySocket;
})

...
  1. You can use this in many ways inside a controller:
    // have your scope listen to socket errors
    $scope.$on('socket:error', function (ev, data) {
      console.log(...);
    });

    // listen to specific events like `myEvent` or whatever event name you choose
    $sockets.on('myEvent', function(id) {
      console.log(...);
    });

    // forward your events to the `$scope` and ...
    $sockets.forward('myEvent', $scope);
    // listen for the `prefix:myEvent` via the scope, if it makes sense given your usecase
    $scope.$on('socket:myEvent', function (ev, data) {
      console.log(...);
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment