Create your first real-time AngularJS application

In my previous article I talked about creating real-time PHP application. That was on the server side and I demonstrated a very very basic client to connect with it. Let’s take that to next step and create a Javascript client with AngularJS.



 css/bootstrap.min.css" rel="stylesheet">
 <script src="angular-client.js"></script>
 body { margin-top: 10px; }
 input.message { height: 30px; }
 <form class="form-inline">
 <button ng-click="connect()" class="btn">Connect</button>
 <input type="text" ng-model="text" placeholder="input message to send" class="message"></input>
 <button ng-click="send()" class="btn">send</button>
 <table class="table table-striped">
 <tr ng-repeat="message in messages">



var app = angular.module('app', []);
app.factory('ChatService', function() {
 var service = {};
 service.connect = function() {
 if( { return; }
 var ws = new WebSocket("ws://localhost:8080");
 ws.onopen = function() {
 service.callback("Succeeded to open a connection");
 ws.onerror = function() {
 service.callback("Failed to open a connection");
 ws.onmessage = function(message) {
 }; = ws;
 service.send = function(message) {;
 service.subscribe = function(callback) {
 service.callback = callback;
 return service;
app.controller('AppCtrl', ['$scope', 'ChatService', function($scope, ChatService) {
 $scope.messages = [];
 ChatService.subscribe(function(message) {
 $scope.connect = function() {
 $scope.send = function() {
 $scope.text = "";


It is pretty straightforward. We created an Angular Service and consumed that in our Angular controller. The only purpose of Angular service is handling communication. It will hand over the message to the subscriber in our case Angular controller and controller can do anything with that message. Here since we demonstrated the chat application so controller displays that message received.

That’s it! so simple.

Note: Both HTML and Javascript files are also available on Gist.

Code was referenced from here.




Ask J

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s