Confused about Service vs Factory

后端 未结 20 2763
轻奢々
轻奢々 2020-11-22 08:49

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

20条回答
  •  没有蜡笔的小新
    2020-11-22 09:28

    Here are the primary differences:

    Services

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

    Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

    Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

    Factories

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

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

    Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

    Also check AngularJS documentation and similar question on stackoverflow confused about service vs factory.

    Here is example using services and factory. Read more about AngularJS service vs factory.

提交回复
热议问题