gpt4 book ai didi

javascript - Socket.io 发出事件不会更新 Angular 控制的元素

转载 作者:行者123 更新时间:2023-11-27 22:53:43 25 4
gpt4 key购买 nike

我为下面的问题做了一个简化的例子。基本上,“this.content”变量不会被“socket.on”事件更改(否则可以正常工作)。

index.html:

<div ng-controller="gameController as game">
<button ng-click="game.buttonClick()">This changes the text when clicked.</button>
<div>{{ game.content }}</div>
</div>

Controller .app:

app.controller('gameController', function($scope, $http) {
this.content = "Default";

this.buttonClick = function() {
this.content = "Content changes to this, when the button is clicked.";
};

socket.on('gameFound', function () {
this.content = "Content doesn't change to this, when a message is emitted.";
console.log("This message is being logged into the console though.");
});
});

在服务器端,我有一个 socket.emit('gameFound', "Something"),它工作正常。

我认为问题在于“this.content”指的是socket.on上下文中的其他内容。

如何更改socket.on函数中“this.content”的值?

感谢任何帮助。

最佳答案

我认为上下文错误,请尝试:

app.controller('gameController', function($scope, $http) {
var self = this;
self.content = "Default";

this.buttonClick = function() {
self.content = "Content changes to this, when the button is clicked.";
};

socket.on('gameFound', function () {
self.content = "Content doesn't change to this, when a message is emitted.";
console.log("This message is being logged into the console though.");
});
});

socket.on 中执行 this.content 实际上意味着 socket.content 而不是 gameController.content你期望的。

另一种方法是:到 bind这是外部环境,

socket.on('gameFound', function () {
this.content = "Content doesn't change to this, when a message is emitted.";
console.log("This message is being logged into the console though.");
}.bind(this));

如果您希望 Angular 在内容更新时更新 View ,则必须手动调用它。 Angular 不知道内容是否更新,因为没有与 DOM 交互。试试这个:

socket.on('gameFound', function () {
self.content = "Content doesn't change to this, when a message is emitted.";
console.log("This message is being logged into the console though.");
// update the view
$scope.$apply();
});

关于javascript - Socket.io 发出事件不会更新 Angular 控制的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37814912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com