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

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -