Answer the question
In order to leave comments, you need to log in
How to properly make a service \ factory with socket.io so that each directive receives its own data?
Hello everyone, we have
main.js
angular.module('app',['btford.socket-io'])
.factory('socket', function (socketFactory) {
var myIoSocket = io.connect('http://localhost');
var mySocket = socketFactory({
ioSocket: myIoSocket
});
return mySocket;
})
.directive('myDir',function(){
return {
restrict: 'E',
scope:{
marker:'@'
},
template: '<p ng-bind="marker"></p><ul><li ng-repeat="item in ItemList"><div ng-bind="item"></div></li></ul>',
controller:function($scope, socket){
socket.emit('joinRoom', $scope.marker );
socket.on('updateEvent',function(data){
$scope.ItemList= data;
});
}
};
})
.controller('main',function($scope, $http){
$http.get('localhost/api/getList')
.success(function(data){
$scope.markerlist = data;
});
});
<html lang="en">
<body ng-app="app">
<div ng-controller='main' class="main">
<div ng-repeat='marker in markerlist'>
<my-dir marker='{{marker}}'></my-dir>
</div>
</div>
</body>
<script src="./libs/socket.io-client/socket.io.js"></script>
<script src="./libs/angular/angular.min.js"></script>
<script src="./libs/angular-socket-io/socket.min.js"></script>
<script src="./js/main.js"></script>
</html>
Answer the question
In order to leave comments, you need to log in
Here's an option that might help:
var myIoSocket = io.connect('http://localhost', {'force new connection': true});
You make a $connections service with a $get method or something like that. If there is no such connection, it will be created, if there is, it will be given ready.
In your case, I would also introduce a room manager, so that it would contain all the logic for joining a specific group, etc. in order to separate this matter from directives as much as possible. That is, in the directive, you simply ask "give me access to such and such a room" and that's it. No emits and generally work with sockets inside directives.
And don't initialize anything inside the factory.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question