Search code examples
angularjsangularjs-serviceangularjs-controllerangularjs-factory

Pass Array from Controller to Factory error


I have a factory thats using angular-websocket to connect with a backend and I need to pass info from my controller to it so that it would send that info and I want to pass it as an array. Factory is as such:

.factory('registerService', function($websocket) {
  var dataStream = $websocket('ws://localhost:3000'); //websocket
  dataStream.onOpen(function() {
    console.log('in');
    this.sendId = function(data) {
    console.log('data: '+data);
    };
  })
  dataStream.send(function(message) {
    //send info to backend
  });
})

And controller as such:

.controller("registerController", function($scope,$stateParams,$ionicPopup,$state,registerService) {
  $scope.registerService = registerService;
  $scope.signUp = function() {
        registerBox = [];
        registerBox.push('Register')
        registerService.sendId(registerBox);
  };
})

However I get error: registerService.sendId is not a function. Whats the problem please?


Solution

  •      .factory('registerService', function($websocket) {
              var dataStream = $websocket('ws://localhost:3000'),
                  _this = this;
    
              dataStream.onOpen(function() {
                console.log('in');
                _this.sendId = function(data) {
                   console.log('data: '+data);
                };
              })
              dataStream.send(function(message) {
                //send info to backend
              });
    
             return _this;
       });