I made the most simple possible application using angular and node. It is a chat application that has an ng-model on a text field.
When the text field value changes, the message is emitted and node sends it out. I assign that value to a variable, but it is always one character behind. I honestly have no idea why.
For example, the text field value is "hello world", and the {{receive}} prints out "hello worl".
What's worse is when I console.log the data it has the full value, I assign it immediately after without altering it at all, and it is missing a character. Am I doing something wrong?
<p>{{receive}}</p>
<input ng-model="msg"></input>
<script>
var app = angular.module('app', []);
app.controller('chat', ['$scope',
function($scope) {
var socket = io.connect();
$scope.msg = '';
$scope.receive = '';
$scope.$watch('msg',function(){
socket.emit('send message', $scope.msg);
});
socket.on('new message', function(data){
console.log(data);
// console.logging results in the entire message
$scope.receive = data;
});
}]);
</script>
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(request, response){
response.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.on('send message', function(data){
io.sockets.emit('new message', data);
});
});
You need to use $scope.$apply to update your bindings when changing it outside of an Angular function.
socket.on('new message', function(data){
console.log(data);
// console.logging results in the entire message
$scope.receive = data;
$scope.$apply();
});
It can also be used like this, which captures any errors thrown inside the function and updates anyway.
socket.on('new message', function(data){
console.log(data);
// console.logging results in the entire message
$scope.$apply(function () {
$scope.receive = data;
});
});