/ /めちゃくちゃシンプルなangular / nodeアプリが期待どおりに機能しない-javascript、node.js、angularjs

面倒な単純な角度/ノードアプリケーションが期待通りに機能しない - javascript、node.js、angularjs

角度とノードを使用して、可能な限り最も単純なアプリケーションを作成しました。これは、テキストフィールドにng-modelがあるチャットアプリケーションです。

テキストフィールドの値が変更されると、メッセージが発行され、ノードがメッセージを送信します。その値を変数に割り当てますが、常に1文字遅れています。正直なところ、理由はわかりません。

たとえば、テキストフィールドの値は「helloworld」であり、{{receive}}は「helloworl」を出力します。

さらに悪いことに、完全な値を持つデータをconsole.logに記録し、まったく変更せずにすぐに割り当て、文字が欠落しています。何か問題がありますか?

<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);
});

});

回答:

回答№1は1

あなたは使用する必要があります $scope.$apply Angular関数の外部でバインディングを変更するときにバインディングを更新します。

socket.on("new message", function(data){
console.log(data);
// console.logging results in the entire message
$scope.receive = data;
$scope.$apply();
});

このように使用することもできます。これは、関数内でスローされたエラーをキャプチャし、とにかく更新します。

socket.on("new message", function(data){
console.log(data);
// console.logging results in the entire message
$scope.$apply(function () {
$scope.receive = data;
});
});