ioのコネクションインスタンスをdiで注入してやらないと正常に動作しないので注意。
下記のようなファクトリーを定義してやればOK。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | coreApp.factory( 'coreSocket' , 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); } }); }); } }; }); 1 これを適宜コントローラーに注入してやればOK。 コントローラーはかきのような感じ。(適当に書いたやつまんまコピペ 1 coreCtrls.controller( 'indexCtrl' , function ($scope, coreSocket, $timeout) { var chatContainer = angular.element( '.messages-container' ); $scope.chatStage = '' ; $scope.remark = function ($event) { if ($event.type == 'keypress' && $event.which != 13) { return false ; } coreSocket.emit( 'chatPosted' , $scope.message); $scope.message = null ; } coreSocket.on( 'chatPosted' , function (msg) { $scope.chatStage += msg + '\n' ; $timeout( function () { chatContainer.scrollTop(chatContainer[0].scrollHeight); }); }); coreSocket.on( 'disconnect' , function () { coreSocket.disconnect(); }); }); |
サーバーサイドはこんな感じ。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | io.on( 'connection' , function (socket) { console.log( 'a user connected' ); socket.on( 'disconnect' , function () { console.log( 'user disconnected' ); }); socket.on( 'chatPosted' , function (msg) { console.log(msg); io.emit( 'chatPosted' , msg); }); }); |
ログインユーザーとかルームとかの概念はまだまだ調査ガ必要だなぁ。