AngularJs + Soket.Io - 套接字初始化

时间:2014-10-05 04:16:14

标签: angularjs socket.io

我已经使用node + socket.io

在angularjs中成功实现了聊天室

但是希望你们可以帮助我,我会陷入一种情况,我会在客户端听到套接字

socket.on('new message', function(data){
     $scope.messages.push(data);//then run ng-repeat in the template
});

问题是,

1)如果我将上述方法放在控制器中,每当我一次又一次打开该页面时,上面的内容会重新初始化(多个侦听器绑定)(我们有多页面应用程序)

2)如果我把上述方法(正如文档所说)放在全球的地方我会失去控制器的范围,所以我不能将最新的模型绑定到模板

任何帮助??

1 个答案:

答案 0 :(得分:0)

您可以尝试在销毁$scope时断开套接字...

$scope.$on('$destroy', function(){
    socket.disconnect();
});

但我喜欢基于服务的方法......

var SocketService = function(){
    var _messages = [];

    socket = connectMeToSomeSocket();

    socket.on('new message', function(data){
       _messages.push(data);
    });

    Object.defineProperty(this, 'messages', {
        get: function(){
           return _messages;
        }
    })
};

然后在您的控制器中注入socketService ...

angular.controller('SomeCtrl',['$scope', 'socketService', function($scope, socketService){
   $scope.socket = socketService;
}])

在模板中使用socket.messages ...

 <li ng-repeat="msg in socket.messages">

如果您不希望模板访问socketService或不喜欢Object.defineProperty,那么您可以添加bindScope方法作为您的服务......

 this.bindScope = function($scope){
   var stopWatching = $scope.$watchCollection(function(){ return _messages;}, function(){
         $scope.messages = _messages;
    });
   // may not be necessary as `Scope` prob cleans up after itself
   $scope.$on('$destroy', stopWatching);
 };

并在你的控制器中使用它......

socketService.bindScope($scope);