Search code examples
angularjsreturnangularjs-serviceangularjs-factory

Use return statement twice in factory


I have a factory code where I need to return methods for use in template and also return _this for use in getting info from the controller to send off via the factory. Problem is I don't know how to put both at the same time as the return picks the first return. How do I add both? Code:

.factory('chatroomService', function($websocket,$rootScope,$state) {
    var dataStream = $websocket('ws://localhost:9000');
    _this = this;
    var collection = ["Ola"];
    dataStream.onOpen(function() {
      _this.sendChat = function(data) {
        dataStream.send(data);
      };
    });
  var methods = {
    collection : collection,
    get: function() {
      dataStream.send(JSON.stringify({action: 'get'}));
    }
  };
    return methods; //problem here
})

Solution

  • You could return an object with both

    return {methods: methods, context: _this}
    

    And to use it you'll call chatroomService.methods or chatroomService.context