Created
September 13, 2014 09:18
-
-
Save mjawaids/cbaf7cba198c56837f1a to your computer and use it in GitHub Desktop.
Real-time AngularJS App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> | |
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> | |
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> | |
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js"></script> | |
<script src="angular-client.js"></script> | |
<style> | |
body { margin-top: 10px; } | |
input.message { height: 30px; } | |
</style> | |
</head> | |
<body ng-app="app" ng-controller="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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = ""; | |
} | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment