Rk Reddy Bairi Rk Reddy Bairi - 1 year ago 68
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() {
var self = this;
self.model = {};
console.log('in the constructor function');
HomeFactory.contactSubmit = function() {
// returning the factory object
return (HomeFactory);

Angular Controller:

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


Answer Source

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

$scope.home1 = new HomeFactory();
$scope.home2 = new HomeFactory();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download