1

I've got this fiddle that creates a functional example of the question.

My understanding of module.factory vs. module.service is that the service function you provide is returned by calling return new serviceFunction while the factory function is called and it's return value provided. I thought one implication of this was that you'd get different instances of the factory result.

I created this factory:

app.factory('fact', function() {
    return Math.random();
});

and then two controllers with the factory injected. I then referenced the result of the factory method as such:

app.controller('test1Controller', ['$scope', 'fact', function ($scope, fact) {
    $scope.fact = fact;
}]);

app.controller('test2Controller', ['$scope', 'fact', function ($scope, fact) {    
    $scope.fact = fact;
}]);

I expected the result to be two different random numbers, but they are the same. How is this possible if the factory method is being called twice?

3
  • 2
    Your assumptions are wrong. Whatever the way you choose to create a service, it's always a singleton. Angular will call your service constructor, or your service factory, or your provider function only once, and reuse the created object. Commented Dec 15, 2014 at 21:00
  • @JBNizet That should be an answer. Commented Dec 15, 2014 at 21:01
  • Well there you go. @JBNizet, put that in an answer and I'm happy to accept it. Commented Dec 15, 2014 at 21:05

1 Answer 1

2

Your assumptions are wrong. Whatever the way you choose to create a service, it's always a singleton. Angular will call your service constructor, or your service factory, or your provider function only once, and reuse the created object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.