I've been trying for days to unsuccessfully get socket.io to play nicely with an Angular module. Initially all I wanted was to dynamically pull the rooms and categories from the database and update those lists on the client side. I didn't want to make two http requests to the API, so now I'm trying to integrate Socket.io with Angular in hopes that I can change and update Socket.io's room list.
However, using btford's socket.io angular module, I've been unable to get any emits from the client side to call the angular module at all. It's like they're not connected. It unfortunately doesn't throw any errors whatsoever, leaving me at a loss for where the disconnect is happening. The chat works fine between users, and chats persist to the database. I just cannot get data from socket.io into angular and back out again.
If any more information is required, please let me know. Here are a few relevant code snippets:
socket factory
app.factory('socket', function (socketFactory) {
return socketFactory({
prefix: '',
ioSocket: io.connect('http://localhost:3000')
});
});
controller
app.controller('socketCtrl', ['socket','$scope', function(socket, $scope){
$scope.messages = [];
socket.on('connect', function () {
socket.on('sendchat2', function(data) {
$scope.messages.push(data);
console.log($scope.messages)
});
});
}])
html head
<head>
<title>Html Test 2</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="/javascripts/angularApp.js"></script>
<script src="/javascripts/socket.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<link rel="stylesheet" type="text/css" href="/stylesheets/style.css">
</head>
sendchat emit in index.ejs
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', message);
socket.emit('sendchat2', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
Thanks for your time, everyone!