javascript - Listen for socket.io in an Angular App -


i'm looking integrate socket.io angular app. i've seen examples of how create service, makes accessible on controller. understand. i'm looking way controllers can react event calls socket.io.

so:

socket.on('user joined', function (data) {});

i can in 1 controller how do all?

you'll want encapsulate socket in service , inject angular controllers needed.

let's make 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);           }         });       })     }   }; }); 

then we'll inject controller , interact (through socket.io api):

function appctrl($scope, socket) {   socket.on('init', function (data) {     $scope.name = data.name;     $scope.users = data.users;   }); } 

you can customize controller need socket service.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -