Rk Reddy Bairi Rk Reddy Bairi - 5 months ago 13
AngularJS Question

How are variables initialized in an angular factory?

I want to know if the constructor function of a angular factory can be used to run some code when the factory is initialized. For example , I have a factory service, where I want to print to console from that whenever the app starts or whenever this factory is called/initialized. Can somebody please explain ?

Angular Factory:

app.factory('HomeFactory', function() {
// create a object using constructor function
var HomeFactory = function() {
console.log('in the constructor function');
};
HomeFactory.contactSubmit = function() {
var self = this;
console.log(self.model);
}
// returning the factory object
return (HomeFactory);
});


Angular Controller:

app.controller('HomeController', function($scope, $state, HomeFactory) {
$scope.HomeFactory = HomeFactory;
}


);

Answer

Factory you create is just a constructor function. you need to instantiate instances to call it:

$scope.home1 = new HomeFactory();
$scope.home2 = new HomeFactory();
Comments