我想使用 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>
正如 Krzystof Safjanowski 在评论中所说,您似乎忘记在 html 中包含 websocket 脚本文件。如果您查看浏览器的控制台(Ctrl+Shift+J
在 Chrome 和 Firefox 中),您应该会看到相关错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句