Answer the question
In order to leave comments, you need to log in
How to get rid of multiple factory call in AngularJS controller when using router?
Good afternoon, there is a factory:
app.factory('socketio', ['$rootScope', function ($rootScope) {
var socket = io.connect('/');
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
}]);
app.controller("some_controller", [
'socketio',
function (socketio) {
var self = this;
socketio.emit('load_data',{});
socketio.on('load_data', function (data) {
// срабатывает пропорцианально открытию роута
console.log(data);
});
}
]);
Answer the question
In order to leave comments, you need to log in
In general, it turned out to be cured with the library https://github.com/btford/angular-socket-io and deleting during destroy, the code may be useful to someone:
app.controller("some_controller", [
'angular-socket-io',
'$scope',
function (socketio, $scope) {
var self = this;
socketio.emit('load_data',{});
socketio.on('load_data', function (data) {
console.log(data);
});
$scope.$on('$destroy', function () {
socket.removeListener('load_data');
});
}
]);
removeListener: function (ev, fn) {
if (fn && fn.__ng) {
arguments[1] = fn.__ng;
}
return socket.removeListener.apply(socket, arguments);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question