Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

As I understand it when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using this and not returning anything.

I was under the assumption that service was always a singleton, and that a new factory object gets injected in every controller. However, as it turns out, a factory object is a singleton too?

Example code to demonstrate:

var factories = angular.module('app.factories', []); 

var app = angular.module('app', ['ngResource', 'app.factories']); 

factories.factory('User', function () { 

return { 

first: 'John', 

last: 'Doe' 

  }; 

}); 

app.controller('ACtrl', function($scope, User) { 

$scope.user = User; 

}); 

app.controller('BCtrl', function($scope, User) {

$scope.user = User; 

});

When changing user.first in ACtrl it turns out that user.first in BCtrl is also changed, e.g. User is a singleton?

My assumption was that a new instance was injected in a controller with a factory?

1 Answer

0 votes
by (106k points)

One important point, it is very important to realize that all Angular services are application singletons. That means there is only one instance of a given service per injector.

The difference between the service and factory can be understood by the below-mentioned code:-

app.service('myService', function() {

this.sayHello = function(name) {

return "Hi " + name + "!"; }; 

}); 

app.factory('myFactory', function() { 

return {

sayHello : function(name) { 

 return "Hi " + name + "!"; 

      } 

   }

});

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+2 votes
1 answer

Browse Categories

...