Socket.io发出事件不会更新Angular受控元素

时间:2016-06-14 14:29:33

标签: 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(&#39; gameFound&#39;,&#34; Something&#34;),它正常工作。

我认为问题是&#34; this.content&#34;在socket.on。

的上下文中指的是其他东西

如何更改&#34; this.content&#34;的值?在socket.on函数?

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我认为背景错误,请尝试:

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

this.content内执行socket.on实际上意味着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不知道内容是否因为没有与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();
});