Angular: PubNub Chat
http://angularjs.org/ http://pubnub.com
by BinaryAcid
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc7.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<div pub-key="pub-8e474368-7add-4283-9b87-caf9efbcdedc" sub-key="sub-1ffec1f3-9463-11e1-9376-77819258e702" ssl="off" origin="pubsub.pubnub.com" id="pubnub"></div>
<script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script>
<div ng-controller="MyCtrl">
<div class="progress progress-striped active" id="progress_bar">
<div class="bar" style="width: 100%;"></div>
</div>
<div class="well">
<b>Status: {{realtimeStatus}} </b>
<form class="form-horizontal">
<label>Name:</label> <input placeholder="Your Name" type="text" name="username" ng-model="message.username"/> <br/>
<label>Message:</label> <input placeholder="What's on your mind?" type="text" name="text" ng-model="message.text"/>
<button type="submit" ng-click="publish()" class="btn btn-primary">Send</button>
</form>
<hr/>
<table class="table table-striped">
<tr ng-repeat="message in messages" cool-fade>
<td><b>{{message.username}} said:</b><br/>
{{message.text}}</td>
</tr>
</table>
</div>
</div>
CSS
label{
font-weight:bold;
}
.well, #progress_bar{
border-radius:0;
margin-top:0;
}
.bar,#progress_bar{
width:100%;
margin-bottom:0;
}
JavaScript
var myApp = angular.module('PubNubChat',[]).directive('coolFade', function() {
return {
compile: function(elm) {
//console.log('compiling');
$(elm).css('opacity', 0);
return function(scope, elm, attrs) {
// console.log('animating');
$(elm).animate({ opacity : 1.0 }, 1000 );
};
}
};
});
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.messages = [];
$scope.realtimeStatus = "Connecting...";
$scope.channel = "pubnub_chat";
$scope.limit = 1;
//publish a chat message
$scope.publish = function(){
//toggle the progress bar
$('#progress_bar').slideToggle();
PUBNUB.publish({
channel : $scope.channel,
message : $scope.message
})
//reset the message text
$scope.message.text = "";
}
//gets the messages history
$scope.history = function(){
PUBNUB.history( {
channel : $scope.channel,
limit : $scope.limit
}, function(messages) {
// Shows All Messages
$scope.$apply(function(){
$scope.messages = messages;
});
} );
}
//we'll leave these ones as is so that pubnub can
//automagically trigger the events
PUBNUB.subscribe({
channel : $scope.channel,
restore : false,
callback : function(message) {
//toggle the progress_bar
$('#progress_bar').slideToggle();
$scope.$apply(function(){
$scope.messages.unshift(message);
});
},
disconnect : function() {
$scope.$apply(function(){
$scope.realtimeStatus =...