Search code examples
angularjsangular-servicesangular-factory

factoy vs service in angular


I have a code which works for both factory and service : I am confused at what circumstances I need to use which code.

This code output my value in console.log using service

var mod = angular.module("MyModule", []);

mod.service("myService", function() {
  console.log("this is service");
    return {
      getvalue : function() {
        return "My value";
      }
  };
});

mod.controller("MyController", function(myService) {
  console.log("MyController - myFactory: " + myService.getvalue());
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyModule">
<div ng-controller="MyController"></div>
</div>

This code I have just change mod.service() to mod.factory() and rest of code is same and it output's my value in console.log using factory

var mod = angular.module("MyModule", []);

mod.service("myFactory", function() {
  console.log("this is Factory");
    return {
      getvalue : function() {
        return "My value";
      }
  };
});

mod.controller("MyController", function(myFactory) {
  console.log("MyController - myFactory: " + myFactory.getvalue());
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyModule">
<div ng-controller="MyController"></div>
</div>


Solution

  • This blog post by Todd Motto is worth a thousands answers.

    Using .factory() gives us much more power and flexibility, whereas a .service() is essentially the “end result” of a .factory() call. The .service() gives us the returned value by calling new on the function, which can be limiting, whereas a .factory() is one-step before this compile process as we get to choose which pattern to implement and return.

    It explains what is the difference at the source code level.

    In real life, my opinion is that it's a matter of taste to use one or the other.

    Coming from Java, I like the fact that .service looks like a class with the use of this.