Matoy
Matoy

Reputation: 1818

How to use socket.io with AngularJS?

I want to create an instant messaging app using Socket.IO and AngularJS.

The var socket = io(); command cancels the AngularJS script. If I delete this line the AngularJS binding works and {{ message }} will display the expected value of the message variable.

However, the code below displays the string "{{ message }}" on my page:

<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> 

Upvotes: 0

Views: 60

Answers (1)

pulse0ne
pulse0ne

Reputation: 1102

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.

Upvotes: 2

Related Questions