I'm going to add some websockets capabilities in my Angular/nodejs application using socket.io.
The final purpose is to keep on server a "live" array of unavailable for writing documents (because someone else is editing them). But I started from the socket.io chat example and I've got stuck very soon.
I'm sure I'm missing something trivial here.
$scope.sendMessage() doesn't emits anything..
FRONT
html
<input type="text" class="form-control" placeholder="message" name="message" ng-model="message"> <button type="button" ng-click="sendMessage()"> sendMessage </button>
socket.io is wrapped in a service
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
controller
$scope.messages=[]
socket.on('init', function (data) {
});
socket.on('send:message', function (message) {
console.log("send:message")
$scope.messages.push(message);
});
$scope.sendMessage = function () {
console.log("send:message")
socket.emit('send:message',$scope.message);
$scope.messages.push($scope.message);
};
SERVER
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('send:message', function (message) {
console.log('send:message:'+message);
socket.broadcast.emit('send:message', {
text:message
});
});
});
emit(send:message)on the client or the handlersocket.on('send:message')on the server. No error at all.