[Update]
$$phaseis an internal, private variable in Angular, and therefore you should not depend on it for such things. In another answer, Igor describes some suggestions for dealing with this that should be used instead (I heard that he knows something about Angular .;)
Angular, Angular . Angular, $apply , Angular , - .
$rootScope.$apply(function () {
callback.apply(socket, args);
});
.. Angular, " , Angular , ".
, $apply, $apply. , $apply already in progress:
$rootScope.$apply(function() {
$rootScope.$apply(function() {
});
});
, , - emit ( $apply) on ( $apply). , $apply, $apply . , $$phase , , .
, , $apply , :
var safeApply = function(scope, fn) {
if (scope.$$phase) {
fn();
} else {
scope.$apply(fn);
}
};
$rootScope.$apply(function...);
safeApply($rootScope, function...);
, , ,
angular.module('app')
.factory('socket', ['$rootScope', function ($rootScope) {
var safeApply = function(scope, fn) {
if (scope.$$phase) {
fn();
} else {
scope.$apply(fn);
}
};
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
safeApply($rootScope, function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
safeApply($rootScope, function () {
if (callback) {
callback.apply(socket, args);
}
});
})
},
disconnect: function () {
socket.disconnect();
},
socket: socket
};
}]);