2016-06-14 52 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