- Install a 3rd party utility to help with wrapping the socket library:
bower install angular-socket-io`
- 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>
- 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;
})
...
- 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(...);
});