nickponline
nickponline

Reputation: 25914

How do you pass parameters to an AngularJS factory?

I have an AngularJS factory that encapsulates a websocket connection. I want to have a number of these used in my controller with each connecting to a different endpoint (specified by personId below)

angular.module('personService', ['ngResource']).
    factory('Person', function($resource) {
        var service = {};

        if (service.ws) { return; }

        var personId = ??? // This will be different for each person.
        var ws = new WebSocket("ws://127.0.0.1:5000/" + personId + "/"); 

        ws.onopen = function() {
          console.log("WebSocket opened");
        };

        ws.onerror = function(err) {
          console.log("WebSocket error " + err);
        }

        ws.onmessage = function(message) {
          service.callback(message.data);
        };

        service.ws = ws;

        service.send = function(message) {
          service.ws.send(message);
        }

        service.subscribe = function(callback) {
          service.callback = callback;
        }

        return service;
      });

function Ctrl($scope, $timeout, Person) {

    $scope.p1 = Person("personId1"); // ??
    $scope.p2 = Person("personId1"); // ??
}

Upvotes: 1

Views: 534

Answers (1)

Joe Minichino
Joe Minichino

Reputation: 2773

update I'm sorry I actually misunderstood you a bit. Define your Person constructor as normal, i.e.

function Person(id) {
  var ws = new Websocket('some url ' + id);
}

then inject into a factory

app.factory('PersonFactory', function () { return Person; });

then in your controller

app.controller('MyCtrl', function ($scope, PersonFactory) {
  $scope.person1 = new PersonFactory(1);
  $scope.person2 = new PersonFactory(2);
}

et voila'.

Upvotes: 2

Related Questions