AngularJS how to get actual factory's data in controller? -
i have factory, when socket messages. how can returned factory's actual data in controller ? please.
app.factory('socket',['$rootscope', function($rootscope) { connection.open(); var connection = new autobahn.connection({ url: 'wss://site.com:6555/', realm: 'realm' }); var collection = { 'topic1': [], 'topic2': [] }; function onevent(args) { console.log("event:", args[0]); collection.topic1.push(args[0]); } connection.onopen = function(session) { session.subscribe(userid, onevent); } return { collection: collection } }]);
the factory cannot push data controller, controller can pull factory. so, inject factory controller:
app.controller('yourcontroller', ['$scope', 'socket', function($scope, socket) { ... $scope.yourcontrollercollection = socket.collection; ... });
if want controller auto-update when socket factory receives event , updates collection, can inject $rootscope factory , $emit event controller can listen to. like:
app.factory('socket',['$rootscope', function($rootscope) { ... function onevent(args) { console.log("event:", args[0]); collection.topic1.push(args[0]); $rootscope.$emit('socketcollectionupdated', collection); // note can name event whatever want. } ... }]); app.controller('yourcontroller', ['$rootscope', '$scope', 'socket', function($rootscope, $scope, socket) { ... $scope.yourcontrollercollection = socket.collection; $rootscope.$on('socketcollectionupdated', function (event, data) { $scope.yourcontrollercollection = data; }); ... });
Comments
Post a Comment