Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Socket.io发出事件不';t更新角控制元件_Javascript_Angularjs_Socket.io - Fatal编程技术网

Javascript Socket.io发出事件不';t更新角控制元件

Javascript Socket.io发出事件不';t更新角控制元件,javascript,angularjs,socket.io,Javascript,Angularjs,Socket.io,我在下面对这个问题做了一个简化的例子。基本上,“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>{{ gam

我在下面对这个问题做了一个简化的例子。基本上,“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>
在服务器端,我有一个socket.emit('gamefind','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

另一种方法是:将它的上下文与外部联系起来

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不知道内容是否已更新,因为没有与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();
});

这很有道理,但它似乎也不这样工作:(编辑:也只是尝试了第二种解决方案,内容没有再次更改。是的,刚刚尝试了一秒钟,但由于某种原因它不工作。控制台记录“GameFind”已正确发出,但是{game.content}的内容保持不变。@Neekoy你不想用angular更新视图吗?angular不知道你更改了值。所以在更改内容后执行
$scope.apply()
。天哪,你太棒了。它给了我一个“非函数错误”,当我用谷歌搜索时,正确的语法是$scope。$apply();成功了。非常感谢。@Neekoy,对不起,我已经一年多没有使用angular:D了,但很高兴它起作用了。
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();
});