2016-06-14 48 views
1

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

的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', “东西”),这是好好工作。

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

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

任何帮助表示赞赏。

回答

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.contentsocket.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(); 
}); 
+0

这使得有很大的意义,但它似乎并没有这样的工作方式无论是:(编辑:只是尝试第二个解决方案也是如此,这些内容并未再次更改 – Neekoy

+0

@Neekoy。你试过'bind'的方法吗? – majidarif

+0

是的,刚刚尝试了一下,因为某些原因,它不起作用。控制台记录'gameFound'是正确发射的,但是{{game.content }}保持一致 – Neekoy