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