To optimize your socket usage in Angular controllers, you should create a service to encapsulate the socket and inject it as necessary.
Here is how you can create a socket service:
app.factory('socket', 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);
}
});
})
}
};
});
Next, we will inject this service into a controller and utilize it using the socket.io
API:
function AppCtrl($scope, socket) {
socket.on('init', function (data) {
$scope.name = data.name;
$scope.users = data.users;
});
}
You have the flexibility to customize the controller based on your requirements with the socket service.