Rk Reddy Bairi Rk Reddy Bairi - 4 months ago 10x
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;
// returning the factory object
return (HomeFactory);

Angular Controller:

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



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

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