user1007665 user1007665 - 1 year ago 61
Node.js Question

failed to combine socket.io with angularJS

I want to create an instance message (chat) app, using Socket.IO and angualrJS.

my code is below. for some reason, the var socket = io(); command "cancel" the angluar script. i.e. if I delete this line the anglaur binding is working and {{ message }} will display its required value. However, when this code is as below, I see the expression: {{ message }} on my page.

how can I combine (on this example) socket.io with angularJS?

Thanks

<html>
<head>
<title>My Chat</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ message }}
<form >
<input autocomplete="off" ng-model="exampleText" type="text" />
<button type='button' ng-click="submit()">
Send
</button>
</form>
</div>
<script>

var app=angular.module("myApp", []);
var socket = io();
app.controller("myCtrl", function($scope) {
$scope.message='';
$scope.submit=function(){
socket.emit('chat message', = angular.copy($scope.exampleText));
return false;
}
socket.on('chat message', function(msg){
$scope=$scope.message+'<li>'+ msg;
});
});
</script>
</body>
</html>

Answer Source

As Krzystof Safjanowski said in his comment, it looks like you're forgetting to include the websocket script file in your html. If you look in your browser's console (Ctrl+Shift+J in Chrome and Firefox), you should see the relevant errors.