Understanding AngularJS Factory and Service

AngularJS service vs factory with example, Understanding AngularJS Factory and Service. Understanding angularjs services. What is an AngularJS service or factory? uses of AngularJS service or factory function.

What is an AngularJS service or factory?

Singleton. Yes! That one word is enough to define AngularJS services. The purpose of AngularJS service / factory function is to generate a single object or function that represents the service to rest of the application. That object or function is passed as a parameter to any other factory function which specifies a dependency on this service.

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. Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

varapp=angular.module(‘myApp’,[]);

// Service definition

app.service(‘testService’,function(){

this.sayHello=function(text){

return“Service says \”Hello “+text+“\””;

};

});

// AngularJS Controller that uses the service

functionHelloCtrl($scope,testService)

{

$scope.fromService=testService.sayHello(“World”);

}

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.