2014-10-05 66 views
0

我已經使用成功實施angularjs聊天室節點+ socket.ioAngularJs + Soket.Io - 端口初始化

但是希望你們能幫助我,我陷在我聽的插座的情況在客戶方

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

問題是,

1)如果我把控制器內的上述方法,上面得到重新初始化(多聽衆結合)每當我一次又一次地打開該頁面(我們擁有多頁app)

2)如果我把上面的方法(如文檔說)在全球地方,我失去了控制的範圍,所以我不能最新型號綁定到模板

任何幫助嗎? ?

回答

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);