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