【问题标题】:How to use socket.io with AngularJS?如何在 AngularJS 中使用 socket.io?
【发布时间】:2016-10-04 09:07:53
【问题描述】:

我想使用 Socket.IO 和 AngularJS 创建一个即时通讯应用。

var socket = io(); 命令取消 AngularJS 脚本。如果我删除这一行,AngularJS 绑定将起作用,{{ message }} 将显示消息变量的预期值。

但是,下面的代码在我的页面上显示字符串“{{ message }}”:

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

【问题讨论】:

  • 您错过了将 socket.io JavaScript 文件添加到 HTML,因此 socket.emitsocket.on 会抛出错误

标签: angularjs node.js socket.io


【解决方案1】:

正如 Krzystof Safjanowski 在评论中所说,您似乎忘记在 html 中包含 websocket 脚本文件。如果您查看浏览器的控制台(Chrome 和 Firefox 中的Ctrl+Shift+J),您应该会看到相关错误。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2013-12-05
    • 2017-03-14
    • 2017-03-05
    • 2013-09-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多