我在下面简要介绍了这个问题。基本上是" 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函数?
感谢任何帮助。
答案 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();
});