AngularJS

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.

Code

angular-client.html


<html>
 <head>
 css/bootstrap.min.css" rel="stylesheet">
 
 
 
 <script src="angular-client.js"></script>
<style>
 body { margin-top: 10px; }
 input.message { height: 30px; }
 </style>
 </head>
 AppCtrl">
 <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>
 </form>
 
 <table class="table table-striped">
 <tr ng-repeat="message in messages">
 <td>{{message}}</td>
 </tr
 </table>
 </body>
</html>

angular-client.js


var app = angular.module('app', []);
app.factory('ChatService', function() {
 var service = {};
 
 service.connect = function() {
 if(service.ws) { 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) {
 service.callback(message.data);
 };
 
 service.ws = ws;
 }
 
 service.send = function(message) {
 service.ws.send(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.messages.push(message);
 $scope.$apply();
 });
 
 $scope.connect = function() {
 ChatService.connect();
 }
 
 $scope.send = function() {
 ChatService.send($scope.text);
 $scope.text = "";
 }
}]);


Details

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.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.