AngularJS how to get actual factory data in controller?

I have a factory when I receive socket messages. How can I get the actual data returned by the factory in my controller? Help me 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
    }

}]);
      

Run codeHide result


0


source to share


2 answers


factory cannot pass data to controller, but controller can pull from factory. To do this, put a factory in the controller:

app.controller('yourController', ['$scope', 'socket', function($scope, socket) {
    ...
    $scope.yourControllerCollection = socket.collection;
    ...
});

      



If you want the controller to automatically update when the factory socket receives an event and updates the collection, you can always inject $ rootScope into the factory and $ emit an event that your controller can listen to. Something 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 that you can name your event whatever you want.
   }
   ...

}]);

app.controller('yourController', ['$rootScope', '$scope', 'socket', function($rootScope, $scope, socket) {
    ...
    $scope.yourControllerCollection = socket.collection;
    $rootScope.$on('SocketCollectionUpdated', function (event, data) {
        $scope.yourControllerCollection = data;
    });
    ...
});

      

+2


source


You want to inject a factory into the controller where you want to use the data. Here's a basic example of passing data from a factory to a controller.

app.factory('sharedData', function() {
 return {
  name: 'Daniel'
 };
});

      

Then in your controller, you can simply set that data object from the factory to the $ scope.



app.controller('MainController', function($scope, sharedData) {
 $scope.data = sharedData;
});

      

So in your case, just create a controller and inject a sockets

factory like this

app.controller('sockets', function($scope, sockets) {
 $scope.collection = collection;
});

      

+1


source







All Articles