I'm working on the project that uses angularjs and
socket.io. I see on some projects that create socket that's a service like that
app.factory('socket', function ($rootScope) {
var socket = io.connect(config.server);
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);
}
});
})
}
};
});
but like that, the socket will connect immediately when the app starts, but I want socket to connect when I click on a button like "Enter the room". I tried:
$scope.rooms= [];
$scope.connectFN= function(){
socket = io.connect(config.server);
$("#btConnectFN").hide();
//connect
socket.on('connect', function(){
console.log("connected");
socket.emit('getRooms');
//listner on get rooms
socket.on('roomList', function(rooms) {
if (rooms.length>0){ //check number of rooms
for (var i=0;i<rooms.length;i++){
console.debug(i);
}
//$scope.rooms.push(5);
$scope.rooms = rooms;
}
});
});
}
But when I run this code, on the side client, $scope.rooms = rooms => that doesn't update the rooms of scope
So anyone can suggest for me how to do that ?
Thank you very much