Kuan
Kuan

Reputation: 11389

How to pass parameter to initialization function of factory in Angular

I wonder when I init a factory, how can I pass params to it, like:

.factory("facObj", function(/*dependency here, but how to put init params*/){
    var facObj = {};
    facObj.name = params.name; // this params is the init params I want to pass in.
})

How to pass that params to factory?

Upvotes: 1

Views: 1270

Answers (3)

sam schonstal
sam schonstal

Reputation: 429

A pattern I use for such a thing looks like this…

Factory code…

angular.module('myApp').factory('MyFactory', function () {

  var myVar;

  function MyFactory(param) {
    myVar = param;
    this.hello = hello;
  }

  function hello() {
    console.log('Hello ' + myVar);
  }

  return MyFactory;
});

Then when using the factory and needing to pass parameters…

angular.module(‘myApp’).controller(‘MyController’ function(MyFactory) {
   myFactory = new MyFactory(‘world’);
   myFactory.hello();
});

Upvotes: 0

Someonation
Someonation

Reputation: 175

Because factories are singletons, they are only initiated once. therefor, the function where you define them is their init. I'm not sure what you are trying to do, but if you want to give the variables in the factory an initial value, you set it hardcoded

.factory("facObj", function(dependency){
    var facObj = {};
    facObj.name = "name";
    return {
      ...
    };
})

if you want to initiate them from a controller, you can define a set method

.factory("facObj", function(dependency){
    var facObj = {};
    var setName = function(newName) {
      facObj.name = newName;
    };
    return {
      ...
      setName:  setName
    };
})

Upvotes: 2

Josh Beam
Josh Beam

Reputation: 19772

You can just expose a method to set whatever internal variables you want:

.factory('facObj', function() {
  var thing;

  return {
    set: function(value) {
      thing = value;
    },
    get: function() {
      return thing;
    }
  }
});


// elsewhere
.controller('MyCtrl', function($scope, facObj) {
   facObj.set('awesome');

   $scope.thing = facObj.get(); // => 'awesome'
});

You can't initialize it with a set of parameters in the way you would normally think. The "contract" so-to-speak of a factory is that it returns an object. You can leverage that object to hold methods that manipulate whatever internal data you have.

Upvotes: 3

Related Questions