【问题标题】:Angular.js - Socket.io event updates model, not viewAngular.js - Socket.io 事件更新模型,而不是视图
【发布时间】:2015-02-25 15:21:19
【问题描述】:

我有套接字工作,因为每个客户端似乎都在运行正确的代码块,控制台记录事件。发送消息的客户端会更新视图,但其他连接的客户端不会。

但是当另一个客户端发送一条消息时,它的视图会更新所有它一直推送到模型的积压消息,所以我知道那部分正在工作。只是视图没有更新。

我已经阅读了一些内容,看起来我需要重构我的代码以使用 $scope$scope.$apply,但我不确定如何使用。

app.controller('StoryController', ['$http', '$scope', function($http, $scope){
    var story = this;

    socket.on('new storyPoint', function(msg){
        //console.log('new storyPoint!', msg);
        story.points.push(msg);
        $('.story').scrollTop($('.story')[0].scrollHeight);
        console.log('last story point:', story.points[story.points.length - 1]);
    });
}]);

如您所见,我实际上还没有使用$scope,而且我很确定我需要这样做,但是尝试模仿其他解决方案来解决这个问题已经失败了。

编辑: 这是视图:

<div class="container story-container" ng-controller="StoryController as storyCtrl">
<aside class="players" id="players"><h1>Players </h1>
    <input name="username" type="text" ng-model="storyCtrl.username"/>
    <ul class="players-list">
        <li>{{storyCtrl.username}}</li>
        <li ng-repeat="player in game.settings.players">{{player}}</li>
    </ul>
</aside>
<div class="main">
    <h1 class="story-title">{{game.settings.title}}</h1>
    <ul class="story">
        <li ng-repeat="storyPoint in storyCtrl.points"><p>{{storyPoint.body}}</p></li>
        <li><p>{{storyCtrl.point.body}}</p></li>
    </ul>
    <form name="storyForm" ng-submit="storyCtrl.addPoint(storyCtrl)">
        <textarea ng-model="storyCtrl.point.body" name="storyPoint" rows="5"></textarea>
        <input class="btn btn-success" type="submit"/>
    </form>
</div>

【问题讨论】:

  • 你能告诉我们你的视图绑定吗?

标签: javascript angularjs socket.io


【解决方案1】:

问题是 Socket.io 不在 Angular 生命周期内,因此 Angular 不知道有新数据进入。你是对的,你需要将 $scope 注入到你的控制器中,然后执行$scope.$apply() 在你的 socket.io 回调中,作为最后一个操作。

$scope.$apply() 让 Angular 知道数据已更新,并刷新需要刷新的内容。

app.controller('StoryController', ['$http', '$scope', function($http, $scope){
    var story = this;

    socket.on('new storyPoint', function(msg){
        //console.log('new storyPoint!', msg);            
        $scope.$apply(function(){
            story.points.push(msg);
            $('.story').scrollTop($('.story')[0].scrollHeight);
            console.log('last story point:', story.points[story.points.length - 1]);             
        });
    });
}]);

【讨论】:

  • 谢谢,我可以发誓我尝试过这个,但由于某种原因它不起作用。我觉得应该是$scope.$apply();
【解决方案2】:

以下代码对我有用,每当您从套接字收到消息时,您只需要将代码绑定到 $scope.$apply() 函数中

 socket.onmessage = function (e) {

            $scope.$apply(function () {
                $scope.onMessge(e);
            });

        };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多