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

标签 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>{{ 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/

相关文章:

javascript - jQuery 代码不适用于 wordpress 网站

javascript - Highcharts 无法通过 AJAX 运行

javascript - 有 Angular 。如何将 json 响应转换为 jsonp 响应?

angularjs - 如何在 Angular ui 网格中将 cellTooltip 与 cellTemplate 一起使用

Javascript 单击切换开始/恢复失败。clearInterval 不起作用

angularjs - 嵌套的ui.bootstrap.accordion 打开所有嵌套的 Accordion

mysql - 连接 MYSQL 数据库时出错(NodeJS、socket.io、express)

node.js - NodeJS 套接字 : Many connections in state CLOSE_WAIT and FIN_WAIT2 without release

javascript - 媒体源 API : Video not playing

javascript - 刷新比。重新加载(无法调用未定义的方法 'authorize')GAPI