0

I have written the following service in angularjs, how/what do I do to change it into a factory? And also, what are the advantages/differences when a factory is used instead of a service?

angular.module('helloApp').service('popupService', function() {
    var popup;

    var setter = function(parameter) {
        popup = parameter;
    };

    var getter = function() {
        return popup;
    };

    return {
        setter: setter,
        getter: getter
    };
});

Thanks in advance

clearScreen
  • 1,002
  • 4
  • 15
  • 31

1 Answers1

1

To change it, you first should declare it in your module as a factory

angular.module('helloApp').factory('popupService', function() {
    var popup;

    var setter = function(parameter) {
        popup = parameter;
    };

    var getter = function() {
        return popup;
    };

    return {
        setter: setter,
        getter: getter
    };
}

This question (factory VS service) is one of the most popular in Stackoverflow : AngularJS: Service vs provider vs factory

Services

Syntax: module.service( 'serviceName', function );

Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().

Factories

Syntax: module.factory( 'factoryName', function );

Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Official documentation

Also you can find official documentation on Angular website :

Community
  • 1
  • 1
sebastienbarbier
  • 6,542
  • 3
  • 29
  • 55