Last Updated: March 21, 2016
· wilk

HTML5 Websocket with AngularJS

It's really cool working with AngularJS and with HTML5 Websockets too!
So, how can I use them together?

With ngWebsocket, indeed!

ngWebsocket is a module created following the Angular-style syntax, very easy to import and use in your application.
Follow a brief tutorial, so all aboard, the Angular ship is ready to go!


You don't have to download a zip from a FTP server, not in 2014, dude.
For front-end libraries, use Bower: it saves time and it's funny, I swear!


bower install ng-websocket

That's it =)


At this point we have to setup our application to include ngWebsocket as a dependency, so let's change the index.html:

<html ng-app="MyAwesomeApp">
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/ng-websocket/ng-websocket.js"></script>

And then the app.js:

'use strict';

angular.module('MyAwesomeApp', ['ngWebsocket']);

Now, you're ready to use it in your application!

Use it

ngWebsocket provides an Angular Provider and a Service.
Let's start with the Service:

angular.controller('MyCtrl', function ($websocket) {
  var ws = $websocket.$new('ws://localhost:12345');

  ws.$on('$open', function () {
    ws.$emit('hello', 'world'); // it sends the event 'hello' with data 'world'
  .$on('incoming event', function (message) { // it listents for 'incoming event'
    console.log('something incoming from the server: ' + message);

As you can see, it's really easy to use, just like working with Events!
No pain, just fun =)

Now, go and start using WebSocket in your application!

Say Thanks

1 Response
Add your response


Thanks for this code snippet. when i try using this code block , i am getting the below error.
var ws = $websocket.$new('ws://localhost:12345'); == $websocket.$new - undefined.

Can you please let us know how to resolve this?

over 1 year ago ·