Rk Reddy Bairi Rk Reddy Bairi - 1 year ago 169
AngularJS Question

How are variables initialized in a angular factory ? (set up init variables)

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 ?

Angualar 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;



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

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