AngularJS: Service vs provider vs factory - angularjs
What are the differences between a Service, Provider and Factory in AngularJS?
From the AngularJS mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. Compiling the answers:
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.
Providers
Syntax: module.provider( 'providerName', function );
Result: When declaring providerName as an injectable argument you will be provided with (new ProviderFunction()).$get(). The constructor function is instantiated before the $get method is called - ProviderFunction is the function reference passed to module.provider.
Providers have the advantage that they can be configured during the module configuration phase.
See here for the provided code.
Here's a great further explanation by Misko:
provide.value('a', 123);
function Controller(a) {
expect(a).toEqual(123);
}
In this case the injector simply returns the value as is. But what if you want to compute the value? Then use a factory
provide.factory('b', function(a) {
return a*2;
});
function Controller(b) {
expect(b).toEqual(246);
}
So factory is a function which is responsible for creating the value. Notice that the factory function can ask for other dependencies.
But what if you want to be more OO and have a class called Greeter?
function Greeter(a) {
this.greet = function() {
return 'Hello ' + a;
}
}
Then to instantiate you would have to write
provide.factory('greeter', function(a) {
return new Greeter(a);
});
Then we could ask for 'greeter' in controller like this
function Controller(greeter) {
expect(greeter instanceof Greeter).toBe(true);
expect(greeter.greet()).toEqual('Hello 123');
}
But that is way too wordy. A shorter way to write this would be provider.service('greeter', Greeter);
But what if we wanted to configure the Greeter class before the injection? Then we could write
provide.provider('greeter2', function() {
var salutation = 'Hello';
this.setSalutation = function(s) {
salutation = s;
}
function Greeter(a) {
this.greet = function() {
return salutation + ' ' + a;
}
}
this.$get = function(a) {
return new Greeter(a);
};
});
Then we can do this:
angular.module('abc', []).config(function(greeter2Provider) {
greeter2Provider.setSalutation('Halo');
});
function Controller(greeter2) {
expect(greeter2.greet()).toEqual('Halo 123');
}
As a side note, service, factory, and value are all derived from provider.
provider.service = function(name, Class) {
provider.provide(name, function() {
this.$get = function($injector) {
return $injector.instantiate(Class);
};
});
}
provider.factory = function(name, factory) {
provider.provide(name, function() {
this.$get = function($injector) {
return $injector.invoke(factory);
};
});
}
provider.value = function(name, value) {
provider.factory(name, function() {
return value;
});
};
JS Fiddle Demo
" Hello world " example with factory / service / provider:
var myApp = angular.module('myApp', []);
//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!";
};
});
//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!";
}
};
});
//provider style, full blown, configurable version
myApp.provider('helloWorld', function() {
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!";
}
}
};
this.setName = function(name) {
this.name = name;
};
});
//hey, we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
{{hellos}}
</div>
</body>
TL;DR
1) When you’re using a Factory you create an object, add properties to it, then return that same object. When you pass this factory into your controller, those properties on the object will now be available in that controller through your factory.
app.controller(‘myFactoryCtrl’, function($scope, myFactory){
$scope.artist = myFactory.getArtist();
});
app.factory(‘myFactory’, function(){
var _artist = ‘Shakira’;
var service = {};
service.getArtist = function(){
return _artist;
}
return service;
});
2) When you’re using Service, AngularJS instantiates it behind the scenes with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will return ‘this’. When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service.
app.controller(‘myServiceCtrl’, function($scope, myService){
$scope.artist = myService.getArtist();
});
app.service(‘myService’, function(){
var _artist = ‘Nelly’;
this.getArtist = function(){
return _artist;
}
});
3) Providers are the only service you can pass into your .config() function. Use a provider when you want to provide module-wide configuration for your service object before making it available.
app.controller(‘myProvider’, function($scope, myProvider){
$scope.artist = myProvider.getArtist();
$scope.data.thingFromConfig = myProvider.thingOnConfig;
});
app.provider(‘myProvider’, function(){
//Only the next two lines are available in the app.config()
this._artist = ‘’;
this.thingFromConfig = ‘’;
this.$get = function(){
var that = this;
return {
getArtist: function(){
return that._artist;
},
thingOnConfig: that.thingFromConfig
}
}
});
app.config(function(myProviderProvider){
myProviderProvider.thingFromConfig = ‘This was set in config’;
});
Non TL;DR
1) Factory
Factories are the most popular way to create and configure a service. There’s really not much more than what the TL;DR said. You just create an object, add properties to it, then return that same object. Then when you pass the factory into your controller, those properties on the object will now be available in that controller through your factory. A more extensive example is below.
app.factory(‘myFactory’, function(){
var service = {};
return service;
});
Now whatever properties we attach to ‘service’ will be available to us when we pass ‘myFactory’ into our controller.
Now let’s add some ‘private’ variables to our callback function. These won’t be directly accessible from the controller, but we will eventually set up some getter/setter methods on ‘service’ to be able to alter these ‘private’ variables when needed.
app.factory(‘myFactory’, function($http, $q){
var service = {};
var baseUrl = ‘https://itunes.apple.com/search?term=’;
var _artist = ‘’;
var _finalUrl = ‘’;
var makeUrl = function(){
_artist = _artist.split(‘ ‘).join(‘+’);
_finalUrl = baseUrl + _artist + ‘&callback=JSON_CALLBACK’;
return _finalUrl
}
return service;
});
Here you’ll notice we’re not attaching those variables/function to ‘service’. We’re simply creating them in order to either use or modify them later.
baseUrl is the base URL that the iTunes API requires
_artist is the artist we wish to lookup
_finalUrl is the final and fully built URL to which we’ll make the call to iTunes
makeUrl is a function that will create and return our iTunes friendly URL.
Now that our helper/private variables and function are in place, let’s add some properties to the ‘service’ object. Whatever we put on ‘service’ can be directly used inside whichever controller we pass ‘myFactory’ into.
We are going to create setArtist and getArtist methods that simply return or set the artist. We are also going to create a method that will call the iTunes API with our created URL. This method is going to return a promise that will fulfill once the data has come back from the iTunes API. If you haven’t had much experience using promises in AngularJS, I highly recommend doing a deep dive on them.
Below setArtist accepts an artist and allows you to set the artist. getArtist returns the artist. callItunes first calls makeUrl() in order to build the URL we’ll use with our $http request. Then it sets up a promise object, makes an $http request with our final url, then because $http returns a promise, we are able to call .success or .error after our request. We then resolve our promise with the iTunes data, or we reject it with a message saying ‘There was an error’.
app.factory('myFactory', function($http, $q){
var service = {};
var baseUrl = 'https://itunes.apple.com/search?term=';
var _artist = '';
var _finalUrl = '';
var makeUrl = function(){
_artist = _artist.split(' ').join('+');
_finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
return _finalUrl;
}
service.setArtist = function(artist){
_artist = artist;
}
service.getArtist = function(){
return _artist;
}
service.callItunes = function(){
makeUrl();
var deferred = $q.defer();
$http({
method: 'JSONP',
url: _finalUrl
}).success(function(data){
deferred.resolve(data);
}).error(function(){
deferred.reject('There was an error')
})
return deferred.promise;
}
return service;
});
Now our factory is complete. We are now able to inject ‘myFactory’ into any controller and we’ll then be able to call our methods that we attached to our service object (setArtist, getArtist, and callItunes).
app.controller('myFactoryCtrl', function($scope, myFactory){
$scope.data = {};
$scope.updateArtist = function(){
myFactory.setArtist($scope.data.artist);
};
$scope.submitArtist = function(){
myFactory.callItunes()
.then(function(data){
$scope.data.artistData = data;
}, function(data){
alert(data);
})
}
});
In the controller above we’re injecting in the ‘myFactory’ service. We then set properties on our $scope object with data from ‘myFactory’. The only tricky code above is if you’ve never dealt with promises before. Because callItunes is returning a promise, we are able to use the .then() method and only set $scope.data.artistData once our promise is fulfilled with the iTunes data. You’ll notice our controller is very ‘thin’ (This is a good coding practise). All of our logic and persistent data is located in our service, not in our controller.
2) Service
Perhaps the biggest thing to know when dealing with creating a Service is that that it’s instantiated with the ‘new’ keyword. For you JavaScript gurus this should give you a big hint into the nature of the code. For those of you with a limited background in JavaScript or for those who aren’t too familiar with what the ‘new’ keyword actually does, let’s review some JavaScript fundamentals that will eventually help us in understanding the nature of a Service.
To really see the changes that occur when you invoke a function with the ‘new’ keyword, let’s create a function and invoke it with the ‘new’ keyword, then let’s show what the interpreter does when it sees the ‘new’ keyword. The end results will both be the same.
First let’s create our Constructor.
var Person = function(name, age){
this.name = name;
this.age = age;
}
This is a typical JavaScript constructor function. Now whenever we invoke the Person function using the ‘new’ keyword, ‘this’ will be bound to the newly created object.
Now let’s add a method onto our Person’s prototype so it will be available on every instance of our Person ‘class’.
Person.prototype.sayName = function(){
alert(‘My name is ‘ + this.name);
}
Now, because we put the sayName function on the prototype, every instance of Person will be able to call the sayName function in order alert that instance’s name.
Now that we have our Person constructor function and our sayName function on its prototype, let’s actually create an instance of Person then call the sayName function.
var tyler = new Person(‘Tyler’, 23);
tyler.sayName(); //alerts ‘My name is Tyler’
So all together the code for creating a Person constructor, adding a function to it’s prototype, creating a Person instance, and then calling the function on its prototype looks like this.
var Person = function(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
alert(‘My name is ‘ + this.name);
}
var tyler = new Person(‘Tyler’, 23);
tyler.sayName(); //alerts ‘My name is Tyler’
Now let’s look at what actually is happening when you use the ‘new’ keyword in JavaScript. First thing you should notice is that after using ‘new’ in our example, we’re able to call a method (sayName) on ‘tyler’ just as if it were an object - that’s because it is.
So first, we know that our Person constructor is returning an object, whether we can see that in the code or not. Second, we know that because our sayName function is located on the prototype and not directly on the Person instance, the object that the Person function is returning must be delegating to its prototype on failed lookups. In more simple terms, when we call tyler.sayName() the interpreter says “OK, I’m going to look on the ‘tyler’ object we just created, locate the sayName function, then call it. Wait a minute, I don’t see it here - all I see is name and age, let me check the prototype. Yup, looks like it’s on the prototype, let me call it.”.
Below is code for how you can think about what the ‘new’ keyword is actually doing in JavaScript. It’s basically a code example of the above paragraph. I’ve put the ‘interpreter view’ or the way the interpreter sees the code inside of notes.
var Person = function(name, age){
//The below line creates an object(obj) that will delegate to the person’s prototype on failed lookups.
//var obj = Object.create(Person.prototype);
//The line directly below this sets ‘this’ to the newly created object
//this = obj;
this.name = name;
this.age = age;
//return this;
}
Now having this knowledge of what the ‘new’ keyword really does in JavaScript, creating a Service in AngularJS should be easier to understand.
The biggest thing to understand when creating a Service is knowing that Services are instantiated with the ‘new’ keyword. Combining that knowledge with our examples above, you should now recognize that you’ll be attaching your properties and methods directly to ‘this’ which will then be returned from the Service itself. Let’s take a look at this in action.
Unlike what we originally did with the Factory example, we don’t need to create an object then return that object because, like mentioned many times before, we used the ‘new’ keyword so the interpreter will create that object, have it delegate to it’s prototype, then return it for us without us having to do the work.
First things first, let’s create our ‘private’ and helper function. This should look very familiar since we did the exact same thing with our factory. I won’t explain what each line does here because I did that in the factory example, if you’re confused, re-read the factory example.
app.service('myService', function($http, $q){
var baseUrl = 'https://itunes.apple.com/search?term=';
var _artist = '';
var _finalUrl = '';
var makeUrl = function(){
_artist = _artist.split(' ').join('+');
_finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
return _finalUrl;
}
});
Now, we’ll attach all of our methods that will be available in our controller to ‘this’.
app.service('myService', function($http, $q){
var baseUrl = 'https://itunes.apple.com/search?term=';
var _artist = '';
var _finalUrl = '';
var makeUrl = function(){
_artist = _artist.split(' ').join('+');
_finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
return _finalUrl;
}
this.setArtist = function(artist){
_artist = artist;
}
this.getArtist = function(){
return _artist;
}
this.callItunes = function(){
makeUrl();
var deferred = $q.defer();
$http({
method: 'JSONP',
url: _finalUrl
}).success(function(data){
deferred.resolve(data);
}).error(function(){
deferred.reject('There was an error')
})
return deferred.promise;
}
});
Now just like in our factory, setArtist, getArtist, and callItunes will be available in whichever controller we pass myService into. Here’s the myService controller (which is almost exactly the same as our factory controller).
app.controller('myServiceCtrl', function($scope, myService){
$scope.data = {};
$scope.updateArtist = function(){
myService.setArtist($scope.data.artist);
};
$scope.submitArtist = function(){
myService.callItunes()
.then(function(data){
$scope.data.artistData = data;
}, function(data){
alert(data);
})
}
});
Like I mentioned before, once you really understand what ‘new’ does, Services are almost identical to factories in AngularJS.
3) Provider
The biggest thing to remember about Providers is that they’re the only service that you can pass into the app.config portion of your application. This is of huge importance if you’re needing to alter some portion of your service object before it’s available everywhere else in your application. Although very similar to Services/Factories, there are a few differences which we’ll discuss.
First we set up our Provider in a similar way we did with our Service and Factory. The variables below are our ‘private’ and helper function.
app.provider('myProvider', function(){
var baseUrl = 'https://itunes.apple.com/search?term=';
var _artist = '';
var _finalUrl = '';
//Going to set this property on the config function below.
this.thingFromConfig = ‘’;
var makeUrl = function(){
_artist = _artist.split(' ').join('+');
_finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
return _finalUrl;
}
}
*Again if any portion of the above code is confusing, check out the Factory section where I explain what it all does it greater details.
You can think of Providers as having three sections. The first section is the ‘private’ variables/functions that will be modified/set later (shown above). The second section is the variables/functions that will be available in your app.config function and are therefore available to alter before they’re available anywhere else (also shown above). It’s important to note that those variables need to be attached to the ‘this’ keyword. In our example, only ‘thingFromConfig’ will be available to alter in the app.config. The third section (shown below) is all the variables/functions that will be available in your controller when you pass in the ‘myProvider’ service into that specific controller.
When creating a service with Provider, the only properties/methods that will be available in your controller are those properties/methods which are returned from the $get() function. The code below puts $get on ‘this’ (which we know will eventually be returned from that function). Now, that $get function returns all the methods/properties we want to be available in the controller. Here’s a code example.
this.$get = function($http, $q){
return {
callItunes: function(){
makeUrl();
var deferred = $q.defer();
$http({
method: 'JSONP',
url: _finalUrl
}).success(function(data){
deferred.resolve(data);
}).error(function(){
deferred.reject('There was an error')
})
return deferred.promise;
},
setArtist: function(artist){
_artist = artist;
},
getArtist: function(){
return _artist;
},
thingOnConfig: this.thingFromConfig
}
}
Now the full Provider code looks like this
app.provider('myProvider', function(){
var baseUrl = 'https://itunes.apple.com/search?term=';
var _artist = '';
var _finalUrl = '';
//Going to set this property on the config function below
this.thingFromConfig = '';
var makeUrl = function(){
_artist = _artist.split(' ').join('+');
_finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'
return _finalUrl;
}
this.$get = function($http, $q){
return {
callItunes: function(){
makeUrl();
var deferred = $q.defer();
$http({
method: 'JSONP',
url: _finalUrl
}).success(function(data){
deferred.resolve(data);
}).error(function(){
deferred.reject('There was an error')
})
return deferred.promise;
},
setArtist: function(artist){
_artist = artist;
},
getArtist: function(){
return _artist;
},
thingOnConfig: this.thingFromConfig
}
}
});
Now just like in our factory and Service, setArtist, getArtist, and callItunes will be available in whichever controller we pass myProvider into. Here’s the myProvider controller (which is almost exactly the same as our factory/Service controller).
app.controller('myProviderCtrl', function($scope, myProvider){
$scope.data = {};
$scope.updateArtist = function(){
myProvider.setArtist($scope.data.artist);
};
$scope.submitArtist = function(){
myProvider.callItunes()
.then(function(data){
$scope.data.artistData = data;
}, function(data){
alert(data);
})
}
$scope.data.thingFromConfig = myProvider.thingOnConfig;
});
As mentioned before, the whole point of creating a service with Provider is to be able to alter some variables through the app.config function before the final object is passed to the rest of the application. Let’s see an example of that.
app.config(function(myProviderProvider){
//Providers are the only service you can pass into app.config
myProviderProvider.thingFromConfig = 'This sentence was set in app.config. Providers are the only service that can be passed into config. Check out the code to see how it works';
});
Now you can see how ‘thingFromConfig’ is as empty string in our provider, but when that shows up in the DOM, it will be ‘This sentence was set…’.
All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.
The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.
The most verbose, but also the most comprehensive one is a Provider
recipe. The remaining four recipe types — Value, Factory, Service and
Constant — are just syntactic sugar on top of a provider recipe.
The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities:
Ability to use other services (have dependencies)
Service initialization
Delayed/lazy initialization
The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.
The Provider recipe is usually overkill. It adds one more layer of indirection by allowing you to configure the creation of the factory.
You should use the Provider recipe only when you want to expose an API
for application-wide configuration that must be made before the
application starts. This is usually interesting only for reusable
services whose behavior might need to vary slightly between
applications.
The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.
See the provider documentation.
Understanding AngularJS Factory, Service and Provider
All of these are used to share reusable singleton objects. It helps to share reusable code across your app/various components/modules.
From Docs Service/Factory:
Lazily instantiated – Angular only instantiates a service/factory when an application component depends on it.
Singletons – Each component
dependent on a service gets a reference to the single instance
generated by the service factory.
Factory
A factory is function where you can manipulate/add logic before creating an object, then the newly created object gets returned.
app.factory('MyFactory', function() {
var serviceObj = {};
//creating an object with methods/functions or variables
serviceObj.myFunction = function() {
//TO DO:
};
//return that object
return serviceObj;
});
Usage
It can be just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are injecting it inside your controller/factory/directive functions. It is instantiated only once per app.
Service
Simply while looking at the services think about the array prototype. A service is a function which instantiates a new object using the 'new' keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains methods/properties).
app.service('MyService', function() {
//directly binding events to this context
this.myServiceFunction = function() {
//TO DO:
};
});
Usage
Use it when you need to share a single object throughout the application. For example, authenticated user details, share-able methods/data, Utility functions etc.
Provider
A provider is used to create a configurable service object. You can configure the service setting from config function. It returns a value by using the $get() function. The $get function gets executed on the run phase in angular.
app.provider('configurableService', function() {
var name = '';
//this method can be be available at configuration time inside app.config.
this.setName = function(newName) {
name = newName;
};
this.$get = function() {
var getName = function() {
return name;
};
return {
getName: getName //exposed object to where it gets injected.
};
};
});
Usage
When you need to provide module-wise configuration for your service object before making it available, eg. suppose you want to set your API URL on basis of your Environment like dev, stage or prod
NOTE
Only provider will be available in config phase of angular, while
service & factory are not.
Hope this has cleared up your understanding about Factory, Service and Provider.
For me, the revelation came when I realized that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through dependency injection.
Say we have:
app.factory('a', fn);
app.service('b', fn);
app.provider('c', fn);
The difference between the three is that:
a's stored value comes from running fn.
b’s stored value comes from newing fn.
c’s stored value comes from first getting an instance by newing fn, and then running a $get method of the instance.
Which means there’s something like a cache object inside AngularJS, whose value of each injection is only assigned once, when they've been injected the first time, and where:
cache.a = fn()
cache.b = new fn()
cache.c = (new fn()).$get()
This is why we use this in services, and define a this.$get in providers.
Service vs provider vs factory:
I am trying to keep it simple. It's all about basic JavaScript concept.
First of all, let's talk about services in AngularJS!
What is Service:
In AngularJS, Service is nothing but a singleton JavaScript object which can store some useful methods or properties. This singleton object is created per ngApp(Angular app) basis and it is shared among all the controllers within current app. When Angularjs instantiate a service object, it register this service object with a unique service name. So each time when we need service instance, Angular search the registry for this service name, and it returns the reference to service object. Such that we can invoke method, access properties etc on the service object.
You may have question whether you can also put properties, methods on scope object of controllers! So why you need service object? Answers is: services are shared among multiple controller scope. If you put some properties/methods in a controller's scope object , it will be available to current scope only. But when you define methods, properties on service object, it will be available globally and can be accessed in any controller's scope by injecting that service.
So if there are three controller scope, let it be controllerA, controllerB and controllerC, all will share same service instance.
<div ng-controller='controllerA'>
<!-- controllerA scope -->
</div>
<div ng-controller='controllerB'>
<!-- controllerB scope -->
</div>
<div ng-controller='controllerC'>
<!-- controllerC scope -->
</div>
How to create a service?
AngularJS provide different methods to register a service. Here we will concentrate on three methods factory(..),service(..),provider(..);
Use this link for code reference
Factory function:
We can define a factory function as below.
factory('serviceName',function fnFactory(){ return serviceInstance;})
AngularJS provides 'factory('serviceName', fnFactory)' method which takes two parameter, serviceName and a JavaScript function. Angular creates service instance by invoking the function fnFactory() such as below.
var serviceInstace = fnFactory();
The passed function can define a object and return that object. AngularJS simply stores this object reference to a variable which is passed as first argument. Anything which is returned from fnFactory will be bound to serviceInstance . Instead of returning object , we can also return function, values etc, Whatever we will return , will be available to service instance.
Example:
var app= angular.module('myApp', []);
//creating service using factory method
app.factory('factoryPattern',function(){
var data={
'firstName':'Tom',
'lastName':' Cruise',
greet: function(){
console.log('hello!' + this.firstName + this.lastName);
}
};
//Now all the properties and methods of data object will be available in our service object
return data;
});
Service Function:
service('serviceName',function fnServiceConstructor(){})
It's the another way, we can register a service. The only difference is the way AngularJS tries to instantiate the service object. This time angular uses 'new' keyword and call the constructor function something like below.
var serviceInstance = new fnServiceConstructor();
In the constructor function we can use 'this' keyword for adding properties/methods to the service object.
example:
//Creating a service using the service method
var app= angular.module('myApp', []);
app.service('servicePattern',function(){
this.firstName ='James';
this.lastName =' Bond';
this.greet = function(){
console.log('My Name is '+ this.firstName + this.lastName);
};
});
Provider function:
Provider() function is the another way for creating services. Let we are interested to create a service which just display some greeting message to the user. But we also want to provide a functionality such that user can set their own greeting message. In technical terms we want to create configurable services. How can we do this ? There must be a way, so that app could pass their custom greeting messages and Angularjs would make it available to factory/constructor function which create our services instance.
In such a case provider() function do the job. using provider() function we can create configurable services.
We can create configurable services using provider syntax as given below.
/*step1:define a service */
app.provider('service',function serviceProviderConstructor(){});
/*step2:configure the service */
app.config(function configureService(serviceProvider){});
How does provider syntax internally work?
1.Provider object is created using constructor function we defined in our provider function.
var serviceProvider = new serviceProviderConstructor();
2.The function we passed in app.config(), get executed. This is called config phase, and here we have a chance to customize our service.
configureService(serviceProvider);
3.Finally service instance is created by calling $get method of serviceProvider.
serviceInstance = serviceProvider.$get()
Sample code for creating service using provide syntax:
var app= angular.module('myApp', []);
app.provider('providerPattern',function providerConstructor(){
//this function works as constructor function for provider
this.firstName = 'Arnold ';
this.lastName = ' Schwarzenegger' ;
this.greetMessage = ' Welcome, This is default Greeting Message' ;
//adding some method which we can call in app.config() function
this.setGreetMsg = function(msg){
if(msg){
this.greetMessage = msg ;
}
};
//We can also add a method which can change firstName and lastName
this.$get = function(){
var firstName = this.firstName;
var lastName = this.lastName ;
var greetMessage = this.greetMessage;
var data={
greet: function(){
console.log('hello, ' + firstName + lastName+'! '+ greetMessage);
}
};
return data ;
};
});
app.config(
function(providerPatternProvider){
providerPatternProvider.setGreetMsg(' How do you do ?');
}
);
Working Demo
Summary:
Factory use a factory function which return a service instance.
serviceInstance = fnFactory();
Service use a constructor function and Angular invoke this constructor function using 'new' keyword for creating the service instance.
serviceInstance = new fnServiceConstructor();
Provider defines a providerConstructor function, this providerConstructor function defines a factory function $get . Angular calls $get() to create the service object. Provider syntax has an added advantage of configuring the service object before it get instantiated.
serviceInstance = $get();
As pointed out by several people here correctly a factory, provider, service, and even value and constant are versions of the same thing. You can dissect the more general provider into all of them. Like so:
Here's the article this image is from:
http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
Factory
You give AngularJS a function, AngularJS will cache and inject the return value when the factory is requested.
Example:
app.factory('factory', function() {
var name = '';
// Return value **is** the object that will be injected
return {
name: name;
}
})
Usage:
app.controller('ctrl', function($scope, factory) {
$scope.name = factory.name;
});
Service
You give AngularJS a function, AngularJS will call new to instantiate it. It is the instance that AngularJS creates that will be cached and injected when the service is requested. Since new was used to instantiate the service, the keyword this is valid and refers to the instance.
Example:
app.service('service', function() {
var name = '';
this.setName = function(newName) {
name = newName;
}
this.getName = function() {
return name;
}
});
Usage:
app.controller('ctrl', function($scope, service) {
$scope.name = service.getName();
});
Provider
You give AngularJS a function, and AngularJS will call its $get function. It is the return value from the $get function that will be cached and injected when the service is requested.
Providers allow you to configure the provider before AngularJS calls the $get method to get the injectible.
Example:
app.provider('provider', function() {
var name = '';
this.setName = function(newName) {
name = newName;
}
this.$get = function() {
return {
name: name
}
}
})
Usage (as an injectable in a controller)
app.controller('ctrl', function($scope, provider) {
$scope.name = provider.name;
});
Usage (configuring the provider before $get is called to create the injectable)
app.config(function(providerProvider) {
providerProvider.setName('John');
});
I noticed something interesting when playing around with providers.
Visibility of injectables is different for providers than it is for services and factories. If you declare an AngularJS "constant" (for example, myApp.constant('a', 'Robert');), you can inject it into services, factories, and providers.
But if you declare an AngularJS "value" (for example., myApp.value('b', {name: 'Jones'});), you can inject it into services and factories, but NOT into the provider-creating function. You can, however, inject it into the $get function that you define for your provider. This is mentioned in the AngularJS documentation, but it's easy to miss. You can find it on the %provide page in the sections on the value and constant methods.
http://jsfiddle.net/R2Frv/1/
<div ng-app="MyAppName">
<div ng-controller="MyCtrl">
<p>from Service: {{servGreet}}</p>
<p>from Provider: {{provGreet}}</p>
</div>
</div>
<script>
var myApp = angular.module('MyAppName', []);
myApp.constant('a', 'Robert');
myApp.value('b', {name: 'Jones'});
myApp.service('greetService', function(a,b) {
this.greeter = 'Hi there, ' + a + ' ' + b.name;
});
myApp.provider('greetProvider', function(a) {
this.firstName = a;
this.$get = function(b) {
this.lastName = b.name;
this.fullName = this.firstName + ' ' + this.lastName;
return this;
};
});
function MyCtrl($scope, greetService, greetProvider) {
$scope.servGreet = greetService.greeter;
$scope.provGreet = greetProvider.fullName;
}
</script>
This is very confusing part for newbie and I have tried to clarify it in easy words
AngularJS Service: is used for sharing utility functions with the service reference in the controller. Service is singleton in nature so for one service only one instance is created in the browser and the same reference is used throughout the page.
In the service, we create function names as property with this object.
AngularJS Factory: the purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object.
AngularJS Provider: the purpose of this is again same however Provider gives the output of it's $get function.
Defining and using Service, Factory and Provider are explained at http://www.dotnetfunda.com/articles/show/3156/difference-between-angularjs-service-factory-and-provider
For me the best and the simplest way of understanding the difference is:
var service, factory;
service = factory = function(injection) {}
How AngularJS instantiates particular components (simplified):
// service
var angularService = new service(injection);
// factory
var angularFactory = factory(injection);
So, for the service, what becomes the AngularJS component is the object instance of the class which is represented by service declaration function. For the factory, it is the result returned from the factory declaration function. The factory may behave the same as the service:
var factoryAsService = function(injection) {
return new function(injection) {
// Service content
}
}
The simplest way of thinking is the following one:
Service is an singleton object instance. Use services if you want to provide a singleton object for your code.
Factory is a class. Use factories if you want to provide custom classes for your code (can't be done with services because they are already instantiated).
The factory 'class' example is provided in the comments around, as well as provider difference.
My clarification on this matter:
Basically all of the mentioned types (service, factory, provider, etc.) are just creating and configuring global variables (that are of course global to the entire application), just as old fashioned global variables were.
While global variables are not recommended, the real usage of these global variables is to provide dependency injection, by passing the variable to the relevant controller.
There are many levels of complications in creating the values for the "global variables":
Constant
This defines an actual constant that should not be modified during the entire application, just like constants in other languages are (something that JavaScript lacks).
Value
This is a modifiable value or object, and it serves as some global variable, that can even be injected when creating other services or factories (see further on these). However, it must be a "literal value", which means that one has to write out the actual value, and cannot use any computation or programming logic (in other words 39 or myText or {prop: "value"} are OK, but 2 +2 is not).
Factory
A more general value, that is possible to be computed right away. It works by passing a function to AngularJS with the logic needed to compute the value and AngularJS executes it, and it saves the return value in the named variable.
Note that it is possible to return a object (in which case it will function similar to a service) or a function (that will be saved in the variable as a callback function).
Service
A service is a more stripped-down version of factory which is valid only when the value is an object, and it allows for writing any logic directly in the function (as if it would be a constructor), as well as declaring and accessing the object properties using the this keyword.
Provider
Unlike a service which is a simplified version of factory, a provider is a more complex, but more flexible way of initializing the "global" variables, with the biggest flexibility being the option to set values from the app.config.
It works like using a combination of service and provider, by passing to provider a function that has properties declared using the this keyword, which can be used from the app.config.
Then it needs to have a separate $.get function which is executed by AngularJS after setting the above properties via the app.config file , and this $.get function behaves just as the factory above, in that its return value is used to initialize the "global" variables.
My understanding is very simple below.
Factory:
You simply create an object inside of the factory and return it.
Service:
You just have a standard function that uses this keyword to define a function.
Provider:
There is a $get object that you define and it can be used to get the object that returns data.
Summary from Angular docs:
There are five recipe types that define how to create objects: Value,
Factory, Service, Provider and Constant.
Factory and Service are the most commonly used recipes. The only difference between them is that the Service recipe works better for objects of a custom type, while the Factory can produce JavaScript primitives and functions.
The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it.
Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration.
Best answers from SO:
https://stackoverflow.com/a/26924234/165673 (<-- GOOD)
https://stackoverflow.com/a/27263882/165673
https://stackoverflow.com/a/16566144/165673
All the good answers already. I would like to add few more points on Service and Factory. Along with the difference between service/factory. And one can also have questions like:
Should I use service or factory? What’s the difference?
Is they do same or have same behaviour?
Lets start with the difference between Service and factory:
Both are Singletons: Whenever Angular find these as a dependency first time,it create a single instance of service/factory. Once the instance is created, same instance is used forever.
Can be used to model an object with behavior: They can both have methods, internal state variables, and so on. Though the way you write that code will differ.
Services:
A service is a constructor function, and Angular will instantiate it by calling new yourServiceName(). This means a couple of things.
Functions and instance variables will be properties of this.
You don’t need to return a value. When Angular calls new yourServiceName(), it’ll receive the this object with all the properties you put on it.
Sample Example:
angular.service('MyService', function() {
this.aServiceVariable = "Ved Prakash"
this.aServiceMethod = function() {
return //code
};
});
When Angular injects this MyService service into a controller that
depends on it, that controller will get a MyService that it can call
functions on, e.g. MyService.aServiceMethod ().
Be careful with this:
Since the constructed service is an object, the methods inside it can refer to this when they’re called:
angular.service('ScoreKeeper', function($http) {
this.score = 0;
this.getScore = function() {
return this.score;
};
this.setScore = function(newScore) {
this.score = newScore;
};
this.addOne = function() {
this.score++;
};
});
You might be tempted to call ScoreKeeper.setScore in a promise chain, for instance if you initialized the score by grabbing it from the server: $http.get('/score').then(ScoreKeeper.setScore). The trouble with this is that ScoreKeeper.setScore will be called with this bound to null and you’ll get errors. The better way would be $http.get('/score').then(ScoreKeeper.setScore.bind(ScoreKeeper)).
Whether you choose to use this in your service methods or not, be careful how you call them.
Returning a Value from a Service:
Due to how JavaScript constructors work, if you return a complex value (i.e., an Object) from a constructor function, the caller will get that Object instead of the this instance.
This means that you can basically copy-paste the factory example from below, replace factory with service, and it’ll work:
angular.service('MyService', function($http) {
var api = {};
api.aServiceMethod= function() {
return $http.get('/users');
};
return api;
});
So when Angular constructs your service with new MyService(), it’ll get that api object instead of the MyService instance.
This is the behavior for any complex values (objects, functions) but not for primitive types.
Factories:
A factory is a plain old function that returns a value. The return value is what gets injected into things that depend on the factory. A typical factory pattern in Angular is to return an object with functions as properties, like this:
angular.factory('MyFactory', function($http) {
var api = {};
api.aFactoryMethod= function() {
return $http.get('/users');
};
return api;
});
The injected value for a factory dependency is the factory’s return
value, and it doesn’t have to be an object. It could be a function
Answers for above 1 and 2 questions:
For the most part, just stick with using factories for everything.
Their behavior is easier to understand. There’s no choice to make
about whether to return a value or not, and furthermore, no bugs to be
introduced if you do the wrong thing.
I still refer to them as “services” when I’m talking about injecting
them as dependencies, though.
Service/Factory behavior is very similar, and some people will say
that either one is fine. That’s somewhat true, but I find it easier to
follow the advice of John Papa’s style guide and just stick with
factories.**
An additional clarification is that factories can create functions/primitives, while services cannot. Check out this jsFiddle based on Epokk's: http://jsfiddle.net/skeller88/PxdSP/1351/.
The factory returns a function that can be invoked:
myApp.factory('helloWorldFromFactory', function() {
return function() {
return "Hello, World!";
};
});
The factory can also return an object with a method that can be invoked:
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!";
}
};
});
The service returns an object with a method that can be invoked:
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!";
};
});
For more details, see a post I wrote on the difference: http://www.shanemkeller.com/tldr-services-vs-factories-in-angular/
There are good answers already, but I just want to share this one.
First of all: Provider is the way/recipe to create a service (singleton object) that suppose to be injected by $injector (how AngulaJS goes about IoC pattern).
And Value, Factory, Service and Constant (4 ways) - the syntactic sugar over Provider way/recepie.
There is Service vs Factory part has been covered:
https://www.youtube.com/watch?v=BLzNCkPn3ao
Service is all about new keyword actually which as we know does 4 things:
creates brand new object
links it to its prototype object
connects context to this
and returns this
And Factory is all about Factory Pattern - contains functions that return Objects like that Service.
ability to use other services (have dependencies)
service initialization
delayed/lazy initialization
And this simple/short video: covers also Provider: https://www.youtube.com/watch?v=HvTZbQ_hUZY (there you see can see how they go from factory to provider)
Provider recipe is used mostly in the app config, before the app has fully started/initialized.
After reading all these post It created more confuse for me.. But still all is worthfull information.. finally I found following table which will give information with simple comparision
The injector uses recipes to create two types of objects: services
and special purpose objects
There are five recipe types that define how to create objects: Value,
Factory, Service, Provider and Constant.
Factory and Service are the most commonly used recipes. The only difference between them is that the Service recipe works better for objects of a custom type, while the Factory can produce JavaScript primitives and functions.
The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it.
Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration.
All special purpose objects except for the Controller are defined via Factory recipes.
And for beginner understand:- This may not correct use case but in high level this is what usecase for these three.
If you want to use in angular module config function should created as provider
angular.module('myApp').config(function($testProvider){
$testProvider.someFunction();
})
Ajax call or third party integrations needs to be service.
For Data manipulations create it as factory
For basic scenarios factory&Service behaves same.
Here is some broilerplate code I've come up with as a code-template for object factory in AngularjS. I've used a Car/CarFactory as an example to illustrate. Makes for simple implementation code in the controller.
<script>
angular.module('app', [])
.factory('CarFactory', function() {
/**
* BroilerPlate Object Instance Factory Definition / Example
*/
this.Car = function() {
// initialize instance properties
angular.extend(this, {
color : null,
numberOfDoors : null,
hasFancyRadio : null,
hasLeatherSeats : null
});
// generic setter (with optional default value)
this.set = function(key, value, defaultValue, allowUndefined) {
// by default,
if (typeof allowUndefined === 'undefined') {
// we don't allow setter to accept "undefined" as a value
allowUndefined = false;
}
// if we do not allow undefined values, and..
if (!allowUndefined) {
// if an undefined value was passed in
if (value === undefined) {
// and a default value was specified
if (defaultValue !== undefined) {
// use the specified default value
value = defaultValue;
} else {
// otherwise use the class.prototype.defaults value
value = this.defaults[key];
} // end if/else
} // end if
} // end if
// update
this[key] = value;
// return reference to this object (fluent)
return this;
}; // end this.set()
}; // end this.Car class definition
// instance properties default values
this.Car.prototype.defaults = {
color: 'yellow',
numberOfDoors: 2,
hasLeatherSeats: null,
hasFancyRadio: false
};
// instance factory method / constructor
this.Car.prototype.instance = function(params) {
return new
this.constructor()
.set('color', params.color)
.set('numberOfDoors', params.numberOfDoors)
.set('hasFancyRadio', params.hasFancyRadio)
.set('hasLeatherSeats', params.hasLeatherSeats)
;
};
return new this.Car();
}) // end Factory Definition
.controller('testCtrl', function($scope, CarFactory) {
window.testCtrl = $scope;
// first car, is red, uses class default for:
// numberOfDoors, and hasLeatherSeats
$scope.car1 = CarFactory
.instance({
color: 'red'
})
;
// second car, is blue, has 3 doors,
// uses class default for hasLeatherSeats
$scope.car2 = CarFactory
.instance({
color: 'blue',
numberOfDoors: 3
})
;
// third car, has 4 doors, uses class default for
// color and hasLeatherSeats
$scope.car3 = CarFactory
.instance({
numberOfDoors: 4
})
;
// sets an undefined variable for 'hasFancyRadio',
// explicitly defines "true" as default when value is undefined
$scope.hasFancyRadio = undefined;
$scope.car3.set('hasFancyRadio', $scope.hasFancyRadio, true);
// fourth car, purple, 4 doors,
// uses class default for hasLeatherSeats
$scope.car4 = CarFactory
.instance({
color: 'purple',
numberOfDoors: 4
});
// and then explicitly sets hasLeatherSeats to undefined
$scope.hasLeatherSeats = undefined;
$scope.car4.set('hasLeatherSeats', $scope.hasLeatherSeats, undefined, true);
// in console, type window.testCtrl to see the resulting objects
});
</script>
Here is a simpler example. I'm using a few third party libraries that expect a "Position" object exposing latitude and longitude, but via different object properties. I didn't want to hack the vendor code, so I adjusted the "Position" objects I was passing around.
angular.module('app')
.factory('PositionFactory', function() {
/**
* BroilerPlate Object Instance Factory Definition / Example
*/
this.Position = function() {
// initialize instance properties
// (multiple properties to satisfy multiple external interface contracts)
angular.extend(this, {
lat : null,
lon : null,
latitude : null,
longitude : null,
coords: {
latitude: null,
longitude: null
}
});
this.setLatitude = function(latitude) {
this.latitude = latitude;
this.lat = latitude;
this.coords.latitude = latitude;
return this;
};
this.setLongitude = function(longitude) {
this.longitude = longitude;
this.lon = longitude;
this.coords.longitude = longitude;
return this;
};
}; // end class definition
// instance factory method / constructor
this.Position.prototype.instance = function(params) {
return new
this.constructor()
.setLatitude(params.latitude)
.setLongitude(params.longitude)
;
};
return new this.Position();
}) // end Factory Definition
.controller('testCtrl', function($scope, PositionFactory) {
$scope.position1 = PositionFactory.instance({latitude: 39, longitude: 42.3123});
$scope.position2 = PositionFactory.instance({latitude: 39, longitude: 42.3333});
}) // end controller
;
Using as reference this page and the documentation (which seems to have greatly improved since the last time I looked), I put together the following real(-ish) world demo which uses 4 of the 5 flavours of provider; Value, Constant, Factory and full blown Provider.
HTML:
<div ng-controller="mainCtrl as main">
<h1>{{main.title}}*</h1>
<h2>{{main.strapline}}</h2>
<p>Earn {{main.earn}} per click</p>
<p>You've earned {{main.earned}} by clicking!</p>
<button ng-click="main.handleClick()">Click me to earn</button>
<small>* Not actual money</small>
</div>
app
var app = angular.module('angularProviders', []);
// A CONSTANT is not going to change
app.constant('range', 100);
// A VALUE could change, but probably / typically doesn't
app.value('title', 'Earn money by clicking');
app.value('strapline', 'Adventures in ng Providers');
// A simple FACTORY allows us to compute a value # runtime.
// Furthermore, it can have other dependencies injected into it such
// as our range constant.
app.factory('random', function randomFactory(range) {
// Get a random number within the range defined in our CONSTANT
return Math.random() * range;
});
// A PROVIDER, must return a custom type which implements the functionality
// provided by our service (see what I did there?).
// Here we define the constructor for the custom type the PROVIDER below will
// instantiate and return.
var Money = function(locale) {
// Depending on locale string set during config phase, we'll
// use different symbols and positioning for any values we
// need to display as currency
this.settings = {
uk: {
front: true,
currency: '£',
thousand: ',',
decimal: '.'
},
eu: {
front: false,
currency: '€',
thousand: '.',
decimal: ','
}
};
this.locale = locale;
};
// Return a monetary value with currency symbol and placement, and decimal
// and thousand delimiters according to the locale set in the config phase.
Money.prototype.convertValue = function(value) {
var settings = this.settings[this.locale],
decimalIndex, converted;
converted = this.addThousandSeparator(value.toFixed(2), settings.thousand);
decimalIndex = converted.length - 3;
converted = converted.substr(0, decimalIndex) +
settings.decimal +
converted.substr(decimalIndex + 1);
converted = settings.front ?
settings.currency + converted :
converted + settings.currency;
return converted;
};
// Add supplied thousand separator to supplied value
Money.prototype.addThousandSeparator = function(value, symbol) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, symbol);
};
// PROVIDER is the core recipe type - VALUE, CONSTANT, SERVICE & FACTORY
// are all effectively syntactic sugar built on top of the PROVIDER construct
// One of the advantages of the PROVIDER is that we can configure it before the
// application starts (see config below).
app.provider('money', function MoneyProvider() {
var locale;
// Function called by the config to set up the provider
this.setLocale = function(value) {
locale = value;
};
// All providers need to implement a $get method which returns
// an instance of the custom class which constitutes the service
this.$get = function moneyFactory() {
return new Money(locale);
};
});
// We can configure a PROVIDER on application initialisation.
app.config(['moneyProvider', function(moneyProvider) {
moneyProvider.setLocale('uk');
//moneyProvider.setLocale('eu');
}]);
// The ubiquitous controller
app.controller('mainCtrl', function($scope, title, strapline, random, money) {
// Plain old VALUE(s)
this.title = title;
this.strapline = strapline;
this.count = 0;
// Compute values using our money provider
this.earn = money.convertValue(random); // random is computed # runtime
this.earned = money.convertValue(0);
this.handleClick = function() {
this.count ++;
this.earned = money.convertValue(random * this.count);
};
});
Working demo.
This answer address the topic/question
how Factory, Service and Constant — are just syntactic sugar on top of a provider recipe?
OR
how factory ,servic and providers are simailar internally
basically what happens is
When you make a factory() it sets you function provided in second argument to provider's $get and return it(provider(name, {$get:factoryFn })), all you get is provider but there is no property/method other than $get of that provider(means you can't configure this)
Source code of factory
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
};
When making a service() it return you providing a factory() with a function that injects the constructor (return the instance of the constructor you provided in your service) and returns it
Source code of service
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
};
So basically in both cases you eventually get a providers $get set to your function you provided , but you can give anything extra than $get as you can originally provide in provider() for config block
I know a lot of excellent answer but I have to share my experience of using
1. service for most cases of default
2. factory used to create the service that specific instance
// factory.js ////////////////////////////
(function() {
'use strict';
angular
.module('myApp.services')
.factory('xFactory', xFactoryImp);
xFactoryImp.$inject = ['$http'];
function xFactoryImp($http) {
var fac = function (params) {
this._params = params; // used for query params
};
fac.prototype.nextPage = function () {
var url = "/_prc";
$http.get(url, {params: this._params}).success(function(data){ ...
}
return fac;
}
})();
// service.js //////////////////////////
(function() {
'use strict';
angular
.module('myApp.services')
.service('xService', xServiceImp);
xServiceImp.$inject = ['$http'];
function xServiceImp($http) {
this._params = {'model': 'account','mode': 'list'};
this.nextPage = function () {
var url = "/_prc";
$http.get(url, {params: this._params}).success(function(data){ ...
}
}
})();
and using:
controller: ['xFactory', 'xService', function(xFactory, xService){
// books = new instance of xFactory for query 'book' model
var books = new xFactory({'model': 'book', 'mode': 'list'});
// accounts = new instance of xFactory for query 'accounts' model
var accounts = new xFactory({'model': 'account', 'mode': 'list'});
// accounts2 = accounts variable
var accounts2 = xService;
...
Little late to the party. But I thought this is more helpful for who would like to learn (or have clarity) on developing Angular JS Custom Services using factory, service and provider methodologies.
I came across this video which explains clearly about factory, service and provider methodologies for developing AngularJS Custom Services:
https://www.youtube.com/watch?v=oUXku28ex-M
Source Code: http://www.techcbt.com/Post/353/Angular-JS-basics/how-to-develop-angularjs-custom-service
Code posted here is copied straight from the above source, to benefit readers.
The code for "factory" based custom service is as follows (which goes with both sync and async versions along with calling http service):
var app = angular.module("app", []);
app.controller('emp', ['$scope', 'calcFactory',
function($scope, calcFactory) {
$scope.a = 10;
$scope.b = 20;
$scope.doSum = function() {
//$scope.sum = calcFactory.getSum($scope.a, $scope.b); //synchronous
calcFactory.getSum($scope.a, $scope.b, function(r) { //aynchronous
$scope.sum = r;
});
};
}
]);
app.factory('calcFactory', ['$http', '$log',
function($http, $log) {
$log.log("instantiating calcFactory..");
var oCalcService = {};
//oCalcService.getSum = function(a,b){
// return parseInt(a) + parseInt(b);
//};
//oCalcService.getSum = function(a, b, cb){
// var s = parseInt(a) + parseInt(b);
// cb(s);
//};
oCalcService.getSum = function(a, b, cb) { //using http service
$http({
url: 'http://localhost:4467/Sum?a=' + a + '&b=' + b,
method: 'GET'
}).then(function(resp) {
$log.log(resp.data);
cb(resp.data);
}, function(resp) {
$log.error("ERROR occurred");
});
};
return oCalcService;
}
]);
The code for "service" methodology for Custom Services (this is pretty similar to 'factory', but different from syntax point of view):
var app = angular.module("app", []);
app.controller('emp', ['$scope', 'calcService', function($scope, calcService){
$scope.a = 10;
$scope.b = 20;
$scope.doSum = function(){
//$scope.sum = calcService.getSum($scope.a, $scope.b);
calcService.getSum($scope.a, $scope.b, function(r){
$scope.sum = r;
});
};
}]);
app.service('calcService', ['$http', '$log', function($http, $log){
$log.log("instantiating calcService..");
//this.getSum = function(a,b){
// return parseInt(a) + parseInt(b);
//};
//this.getSum = function(a, b, cb){
// var s = parseInt(a) + parseInt(b);
// cb(s);
//};
this.getSum = function(a, b, cb){
$http({
url: 'http://localhost:4467/Sum?a=' + a + '&b=' + b,
method: 'GET'
}).then(function(resp){
$log.log(resp.data);
cb(resp.data);
},function(resp){
$log.error("ERROR occurred");
});
};
}]);
The code for "provider" methodology for Custom Services (this is necessary, if you would like to develop service which could be configured):
var app = angular.module("app", []);
app.controller('emp', ['$scope', 'calcService', function($scope, calcService){
$scope.a = 10;
$scope.b = 20;
$scope.doSum = function(){
//$scope.sum = calcService.getSum($scope.a, $scope.b);
calcService.getSum($scope.a, $scope.b, function(r){
$scope.sum = r;
});
};
}]);
app.provider('calcService', function(){
var baseUrl = '';
this.config = function(url){
baseUrl = url;
};
this.$get = ['$log', '$http', function($log, $http){
$log.log("instantiating calcService...")
var oCalcService = {};
//oCalcService.getSum = function(a,b){
// return parseInt(a) + parseInt(b);
//};
//oCalcService.getSum = function(a, b, cb){
// var s = parseInt(a) + parseInt(b);
// cb(s);
//};
oCalcService.getSum = function(a, b, cb){
$http({
url: baseUrl + '/Sum?a=' + a + '&b=' + b,
method: 'GET'
}).then(function(resp){
$log.log(resp.data);
cb(resp.data);
},function(resp){
$log.error("ERROR occurred");
});
};
return oCalcService;
}];
});
app.config(['calcServiceProvider', function(calcServiceProvider){
calcServiceProvider.config("http://localhost:4467");
}]);
Finally the UI which works with any of the above services:
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" ></script>
<script type="text/javascript" src="t03.js"></script>
</head>
<body ng-app="app">
<div ng-controller="emp">
<div>
Value of a is {{a}},
but you can change
<input type=text ng-model="a" /> <br>
Value of b is {{b}},
but you can change
<input type=text ng-model="b" /> <br>
</div>
Sum = {{sum}}<br>
<button ng-click="doSum()">Calculate</button>
</div>
</body>
</html>
Just to clarify things, from the AngularJS source, you can see a service just calls the factory function which in turn calls the provider function:
function factory(name, factoryFn) {
return provider(name, { $get: factoryFn });
}
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course)
SERVICE:
Syntax:
app.js
var app = angular.module('ServiceExample',[]);
var serviceExampleController =
app.controller('ServiceExampleController', ServiceExampleController);
var serviceExample = app.service('NameOfTheService', NameOfTheService);
ServiceExampleController.$inject = ['NameOfTheService'] //protects from minification of js files
function ServiceExampleController(NameOfTheService){
serviceExampleController = this;
serviceExampleController.data = NameOfTheService.getSomeData();
}
function NameOfTheService(){
nameOfTheService = this;
nameOfTheService.data = "Some Data";
nameOfTheService.getSomeData = function(){
return nameOfTheService.data;
}
}
index.html
<div ng-controller = "ServiceExampleController as serviceExample">
{{serviceExample.data}}
</div>
Features of Service:
Lazily Instantiated: If it is not injected it won't be instantiated ever. So to use it will have to inject it to a module.
Singleton: If injected to multiple modules, all will have access to only one particular instance. That is why very convenient to share data across different controllers.
FACTORY
First let's have a look at the syntax:
app.js:
var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);
//first implementation where it returns a function
function NameOfTheFactoryOne(){
var factory = function(){
return new SomeService();
}
return factory;
}
//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
var factory = {
getSomeService : function(){
return new SomeService();
}
};
return factory;
}
Now using the above two in the controller:
var factoryOne = NameOfTheFactoryOne() //since it returns a function
factoryOne.someMethod();
var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
factoryTwo.someMethod();
Features of Factory:
Follows the factory design pattern. The factory is a central place that produces new objects or functions.
Not only produces singleton, but customizable services.
The .service() method is a factory that always produces the same type of service, which is a singleton, and without any easy way to configure it's behavior. That .service() method is usually used as a shortcut for something that doesn't require any configuration whatsoever.
PROVIDER
Let's again have a look at the Syntax first:
angular.module('ProviderModule', [])
.controller('ProviderModuleController', ProviderModuleController)
.provider('ServiceProvider', ServiceProvider)
.config(Config); //optional
Config.$inject = ['ServiceProvider'];
function Config(ServiceProvider) {
ServiceProvider.defaults.maxItems = 10; //some default value
}
ProviderModuleController.$inject = ['ServiceProvider'];
function ProviderModuleController(ServiceProvider) {
//some methods
}
function ServiceProvider() {
var provider = this;
provider.defaults = {
maxItems: 10
};
provider.$get = function () {
var someList = new someListService(provider.defaults.maxItems);
return someList;
};
}
}
Features of Provider:
Provider is the most flexible method of creating services in Angular.
Not only we can create a factory that's dynamically configurable, but at the time of using the factory, with the provider method, we could custom configure the factory just once at the bootstrapping of our entire application.
The factory can then be used throughout the application with custom settings. In other words, we can configure this factory before the application starts. In fact in the angular documentation it is mentioned that the provider method is what actually gets executed behind the scenes when we configure our services with either .service or .factory methods.
The $get is a function that is directly attached to the provider instance. That function is a factory function. In other words, it's just like the one that we use to provide to the .factory method. In that function, we create our own service. This $get property, that's a function, is what makes the provider a provider. AngularJS expects the provider to have a $get property whose value is a function that Angular will treat as a factory function. But what makes this whole provider setup very special, is the fact that we can provide some config object inside the service provider, and that usually comes with defaults that we can later overwrite in the step, where we can configure the entire application.
Essentially, Provider, Factory, and Service are all Services. A Factory is a special case of a Service when all you need is a $get() function, allowing you to write it with less code.
The major differences among Services, Factories, and Providers are their complexities. Services are the simplest form, Factories are a little more robust, and Providers are configurable at runtime.
Here is a summary of when to use each:
Factory: The value you are providing needs to be calculated based on other data.
Service: You are returning an object with methods.
Provider: You want to be able to configure, during the config phase, the object that is going to be created before it’s created. Use the Provider mostly in the app config, before the app has fully initialized.
Factory: The factory you actually create an object inside of the factory and return it.
service: The service you just have a standard function that uses the this keyword to define function.
provider: The provider there’s a $get you define and it can be used to get the object that returns the data.
1.Services are singleton objects that are created when necessary and are never cleaned up until the end of the application life-cycle (when the browser is closed). Controllers are destroyed and cleaned up when they are no longer needed.
2.The easiest way to create a service is by using the factory() method.
The factory() method allows us to define a service by returning an object that contains service functions and service data. The service definition function is where we place our injectable services, such as $http and $q.
Ex:
angular.module('myApp.services')
.factory('User', function($http) { // injectables go here
var backendUrl = "http://localhost:3000"; var service = {
// our factory definition
user: {},
setName: function(newName) {
service.user['name'] = newName;
},
setEmail: function(newEmail) { service.user['email'] = newEmail;
},
save: function() {
return $http.post(backendUrl + '/users', { user: service.user
}); }
};
return service; });
Using the factory() in our app
It’s easy to use the factory in our application as we can simply inject it where we need it at run-time.
angular.module('myApp')
.controller('MainController', function($scope, User) {
$scope.saveUser = User.save;
});
The service() method, on the other hand allows us to create a service by defining a constructor function. We can use a prototypical object to define our service, instead of a raw javascript object.
Similar to the factory() method, we’ll also set the injectables in the function definition.
The lowest level way to create a service is by using the provide() method. This is the only way to create a service that we can configure using the .config() function.
Unlike the previous to methods, we’ll set the injectables in a defined this.$get() function definition.
Syntactic Sugar is the difference. Only provider is needed. Or in other words only provider is the real angular, all other ones are derived(to reduce code). There is a simple version as well, called Value() which returns just the value, no calculation or function. Even Value is derived from provider!
So why such complications, why can't we just use provider and forget everything else? It is supposed to help us write code easily and communicate better. And toungue-in-cheek reply would be, the more complex it gets the better selling a framework will be.
A provider that can return value = Value
A provider that can just
instantiate and return = Factory (+ Value)
A provider that can
instantiate + do something = Service (+ Factory, + Value)
A provider
= must contain a property called $get (+Factory, + Service, + Value)
Angular injection gives us the first hint in reaching this conclusion.
"$injector is used to retrieve object instances as defined by provider" not service, not factory but provider.
And a better answer would be this:
"An Angular service is created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function."
So master provider and injector and all will fall in place :) . And it gets interesting in Typescript when $get can be implemented in a provider by inheriting from IServiceProvider.
Related
$injector:unpr when trying to add service [duplicate]
I have a Service: angular.module('cfd') .service('StudentService', [ '$http', function ($http) { // get some data via the $http var path = 'data/people/students.json'; var students = $http.get(path).then(function (resp) { return resp.data; }); //save method create a new student if not already exists //else update the existing object this.save = function (student) { if (student.id == null) { //if this is new student, add it in students array $scope.students.push(student); } else { //for existing student, find this student using id //and update it. for (i in students) { if (students[i].id == student.id) { students[i] = student; } } } }; But when I call save(), I don't have access to the $scope, and get ReferenceError: $scope is not defined. So the logical step (for me), is to provide save() with the $scope, and thus I must also provide/inject it to the service. So if I do that like so: .service('StudentService', [ '$http', '$scope', function ($http, $scope) { I get the following error: Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- StudentService The link in the error (wow that is neat!) lets me know it is injector related, and might have to do with order of declaration of the js files. I have tried reordering them in the index.html, but I think it is something more simple, such as the way I am injecting them. Using Angular-UI and Angular-UI-Router
The $scope that you see being injected into controllers is not some service (like the rest of the injectable stuff), but is a Scope object. Many scope objects can be created (usually prototypically inheriting from a parent scope). The root of all scopes is the $rootScope and you can create a new child-scope using the $new() method of any scope (including the $rootScope). The purpose of a Scope is to "glue together" the presentation and the business logic of your app. It does not make much sense to pass a $scope into a service. Services are singleton objects used (among other things) to share data (e.g. among several controllers) and generally encapsulate reusable pieces of code (since they can be injected and offer their "services" in any part of your app that needs them: controllers, directives, filters, other services etc). I am sure, various approaches would work for you. One is this: Since the StudentService is in charge of dealing with student data, you can have the StudentService keep an array of students and let it "share" it with whoever might be interested (e.g. your $scope). This makes even more sense, if there are other views/controllers/filters/services that need to have access to that info (if there aren't any right now, don't be surprised if they start popping up soon). Every time a new student is added (using the service's save() method), the service's own array of students will be updated and every other object sharing that array will get automatically updated as well. Based on the approach described above, your code could look like this: angular. module('cfd', []). factory('StudentService', ['$http', '$q', function ($http, $q) { var path = 'data/people/students.json'; var students = []; // In the real app, instead of just updating the students array // (which will be probably already done from the controller) // this method should send the student data to the server and // wait for a response. // This method returns a promise to emulate what would happen // when actually communicating with the server. var save = function (student) { if (student.id === null) { students.push(student); } else { for (var i = 0; i < students.length; i++) { if (students[i].id === student.id) { students[i] = student; break; } } } return $q.resolve(student); }; // Populate the students array with students from the server. $http.get(path).then(function (response) { response.data.forEach(function (student) { students.push(student); }); }); return { students: students, save: save }; }]). controller('someCtrl', ['$scope', 'StudentService', function ($scope, StudentService) { $scope.students = StudentService.students; $scope.saveStudent = function (student) { // Do some $scope-specific stuff... // Do the actual saving using the StudentService. // Once the operation is completed, the $scope's `students` // array will be automatically updated, since it references // the StudentService's `students` array. StudentService.save(student).then(function () { // Do some more $scope-specific stuff, // e.g. show a notification. }, function (err) { // Handle the error. }); }; } ]); One thing you should be careful about when using this approach is to never re-assign the service's array, because then any other components (e.g. scopes) will be still referencing the original array and your app will break. E.g. to clear the array in StudentService: /* DON'T DO THAT */ var clear = function () { students = []; } /* DO THIS INSTEAD */ var clear = function () { students.splice(0, students.length); } See, also, this short demo. LITTLE UPDATE: A few words to avoid the confusion that may arise while talking about using a service, but not creating it with the service() function. Quoting the docs on $provide: An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function. [...] ...the $provide service has additional helper methods to register services without specifying a provider: provider(provider) - registers a service provider with the $injector constant(obj) - registers a value/object that can be accessed by providers and services. value(obj) - registers a value/object that can only be accessed by services, not providers. factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function. service(class) - registers a constructor function, class that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function. Basically, what it says is that every Angular service is registered using $provide.provider(), but there are "shortcut" methods for simpler services (two of which are service() and factory()). It all "boils down" to a service, so it doesn't make much difference which method you use (as long as the requirements for your service can be covered by that method). BTW, provider vs service vs factory is one of the most confusing concepts for Angular new-comers, but fortunately there are plenty of resources (here on SO) to make things easier. (Just search around.) (I hope that clears it up - let me know if it doesn't.)
Instead of trying to modify the $scope within the service, you can implement a $watch within your controller to watch a property on your service for changes and then update a property on the $scope. Here is an example you might try in a controller: angular.module('cfd') .controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) { $scope.students = null; (function () { $scope.$watch(function () { return StudentService.students; }, function (newVal, oldVal) { if ( newValue !== oldValue ) { $scope.students = newVal; } }); }()); }]); One thing to note is that within your service, in order for the students property to be visible, it needs to be on the Service object or this like so: this.students = $http.get(path).then(function (resp) { return resp.data; });
Well (a long one) ... if you insist to have $scope access inside a service, you can: Create a getter/setter service ngapp.factory('Scopes', function (){ var mem = {}; return { store: function (key, value) { mem[key] = value; }, get: function (key) { return mem[key]; } }; }); Inject it and store the controller scope in it ngapp.controller('myCtrl', ['$scope', 'Scopes', function($scope, Scopes) { Scopes.store('myCtrl', $scope); }]); Now, get the scope inside another service ngapp.factory('getRoute', ['Scopes', '$http', function(Scopes, $http){ // there you are var $scope = Scopes.get('myCtrl'); }]);
Services are singletons, and it is not logical for a scope to be injected in service (which is case indeed, you cannot inject scope in service). You can pass scope as a parameter, but that is also a bad design choice, because you would have scope being edited in multiple places, making it hard for debugging. Code for dealing with scope variables should go in controller, and service calls go to the service.
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously. The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance, var students = $http.get(path).then(function (resp) { return resp.data; }); // then() returns a promise object, not resp.data There's a simple way to get around this and it's to supply a callback function. .service('StudentService', [ '$http', function ($http) { // get some data via the $http var path = '/students'; //save method create a new student if not already exists //else update the existing object this.save = function (student, doneCallback) { $http.post( path, { params: { student: student } } ) .then(function (resp) { doneCallback(resp.data); // when the async http call is done, execute the callback }); } .controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) { $scope.saveUser = function (user) { StudentService.save(user, function (data) { $scope.message = data; // I'm assuming data is a string error returned from your REST API }) } }]); The form: <div class="form-message">{{message}}</div> <div ng-controller="StudentSaveController"> <form novalidate class="simple-form"> Name: <input type="text" ng-model="user.name" /><br /> E-mail: <input type="email" ng-model="user.email" /><br /> Gender: <input type="radio" ng-model="user.gender" value="male" />male <input type="radio" ng-model="user.gender" value="female" />female<br /> <input type="button" ng-click="reset()" value="Reset" /> <input type="submit" ng-click="saveUser(user)" value="Save" /> </form> </div> This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
Got into the same predicament. I ended up with the following. So here I am not injecting the scope object into the factory, but setting the $scope in the controller itself using the concept of promise returned by $http service. (function () { getDataFactory = function ($http) { return { callWebApi: function (reqData) { var dataTemp = { Page: 1, Take: 10, PropName: 'Id', SortOrder: 'Asc' }; return $http({ method: 'GET', url: '/api/PatientCategoryApi/PatCat', params: dataTemp, // Parameters to pass to external service headers: { 'Content-Type': 'application/Json' } }) } } } patientCategoryController = function ($scope, getDataFactory) { alert('Hare'); var promise = getDataFactory.callWebApi('someDataToPass'); promise.then( function successCallback(response) { alert(JSON.stringify(response.data)); // Set this response data to scope to use it in UI $scope.gridOptions.data = response.data.Collection; }, function errorCallback(response) { alert('Some problem while fetching data!!'); }); } patientCategoryController.$inject = ['$scope', 'getDataFactory']; getDataFactory.$inject = ['$http']; angular.module('demoApp', []); angular.module('demoApp').controller('patientCategoryController', patientCategoryController); angular.module('demoApp').factory('getDataFactory', getDataFactory); }());
Code for dealing with scope variables should go in controller, and service calls go to the service. You can inject $rootScope for the purpose of using $rootScope.$broadcast and $rootScope.$on. Otherwise avoid injecting $rootScope. See Common Pitfalls: $rootScope exists, but it can be used for evil.
AngularJS and Typescript - Creating a service, factory and provider [duplicate]
What are the differences between a Service, Provider and Factory in AngularJS?
From the AngularJS mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. Compiling the answers: 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. Providers Syntax: module.provider( 'providerName', function ); Result: When declaring providerName as an injectable argument you will be provided with (new ProviderFunction()).$get(). The constructor function is instantiated before the $get method is called - ProviderFunction is the function reference passed to module.provider. Providers have the advantage that they can be configured during the module configuration phase. See here for the provided code. Here's a great further explanation by Misko: provide.value('a', 123); function Controller(a) { expect(a).toEqual(123); } In this case the injector simply returns the value as is. But what if you want to compute the value? Then use a factory provide.factory('b', function(a) { return a*2; }); function Controller(b) { expect(b).toEqual(246); } So factory is a function which is responsible for creating the value. Notice that the factory function can ask for other dependencies. But what if you want to be more OO and have a class called Greeter? function Greeter(a) { this.greet = function() { return 'Hello ' + a; } } Then to instantiate you would have to write provide.factory('greeter', function(a) { return new Greeter(a); }); Then we could ask for 'greeter' in controller like this function Controller(greeter) { expect(greeter instanceof Greeter).toBe(true); expect(greeter.greet()).toEqual('Hello 123'); } But that is way too wordy. A shorter way to write this would be provider.service('greeter', Greeter); But what if we wanted to configure the Greeter class before the injection? Then we could write provide.provider('greeter2', function() { var salutation = 'Hello'; this.setSalutation = function(s) { salutation = s; } function Greeter(a) { this.greet = function() { return salutation + ' ' + a; } } this.$get = function(a) { return new Greeter(a); }; }); Then we can do this: angular.module('abc', []).config(function(greeter2Provider) { greeter2Provider.setSalutation('Halo'); }); function Controller(greeter2) { expect(greeter2.greet()).toEqual('Halo 123'); } As a side note, service, factory, and value are all derived from provider. provider.service = function(name, Class) { provider.provide(name, function() { this.$get = function($injector) { return $injector.instantiate(Class); }; }); } provider.factory = function(name, factory) { provider.provide(name, function() { this.$get = function($injector) { return $injector.invoke(factory); }; }); } provider.value = function(name, value) { provider.factory(name, function() { return value; }); };
JS Fiddle Demo " Hello world " example with factory / service / provider: var myApp = angular.module('myApp', []); //service style, probably the simplest one myApp.service('helloWorldFromService', function() { this.sayHello = function() { return "Hello, World!"; }; }); //factory style, more involved but more sophisticated myApp.factory('helloWorldFromFactory', function() { return { sayHello: function() { return "Hello, World!"; } }; }); //provider style, full blown, configurable version myApp.provider('helloWorld', function() { this.name = 'Default'; this.$get = function() { var name = this.name; return { sayHello: function() { return "Hello, " + name + "!"; } } }; this.setName = function(name) { this.name = name; }; }); //hey, we can configure a provider! myApp.config(function(helloWorldProvider){ helloWorldProvider.setName('World'); }); function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) { $scope.hellos = [ helloWorld.sayHello(), helloWorldFromFactory.sayHello(), helloWorldFromService.sayHello()]; } <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="myApp"> <div ng-controller="MyCtrl"> {{hellos}} </div> </body>
TL;DR 1) When you’re using a Factory you create an object, add properties to it, then return that same object. When you pass this factory into your controller, those properties on the object will now be available in that controller through your factory. app.controller(‘myFactoryCtrl’, function($scope, myFactory){ $scope.artist = myFactory.getArtist(); }); app.factory(‘myFactory’, function(){ var _artist = ‘Shakira’; var service = {}; service.getArtist = function(){ return _artist; } return service; }); 2) When you’re using Service, AngularJS instantiates it behind the scenes with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will return ‘this’. When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. app.controller(‘myServiceCtrl’, function($scope, myService){ $scope.artist = myService.getArtist(); }); app.service(‘myService’, function(){ var _artist = ‘Nelly’; this.getArtist = function(){ return _artist; } }); 3) Providers are the only service you can pass into your .config() function. Use a provider when you want to provide module-wide configuration for your service object before making it available. app.controller(‘myProvider’, function($scope, myProvider){ $scope.artist = myProvider.getArtist(); $scope.data.thingFromConfig = myProvider.thingOnConfig; }); app.provider(‘myProvider’, function(){ //Only the next two lines are available in the app.config() this._artist = ‘’; this.thingFromConfig = ‘’; this.$get = function(){ var that = this; return { getArtist: function(){ return that._artist; }, thingOnConfig: that.thingFromConfig } } }); app.config(function(myProviderProvider){ myProviderProvider.thingFromConfig = ‘This was set in config’; }); Non TL;DR 1) Factory Factories are the most popular way to create and configure a service. There’s really not much more than what the TL;DR said. You just create an object, add properties to it, then return that same object. Then when you pass the factory into your controller, those properties on the object will now be available in that controller through your factory. A more extensive example is below. app.factory(‘myFactory’, function(){ var service = {}; return service; }); Now whatever properties we attach to ‘service’ will be available to us when we pass ‘myFactory’ into our controller. Now let’s add some ‘private’ variables to our callback function. These won’t be directly accessible from the controller, but we will eventually set up some getter/setter methods on ‘service’ to be able to alter these ‘private’ variables when needed. app.factory(‘myFactory’, function($http, $q){ var service = {}; var baseUrl = ‘https://itunes.apple.com/search?term=’; var _artist = ‘’; var _finalUrl = ‘’; var makeUrl = function(){ _artist = _artist.split(‘ ‘).join(‘+’); _finalUrl = baseUrl + _artist + ‘&callback=JSON_CALLBACK’; return _finalUrl } return service; }); Here you’ll notice we’re not attaching those variables/function to ‘service’. We’re simply creating them in order to either use or modify them later. baseUrl is the base URL that the iTunes API requires _artist is the artist we wish to lookup _finalUrl is the final and fully built URL to which we’ll make the call to iTunes makeUrl is a function that will create and return our iTunes friendly URL. Now that our helper/private variables and function are in place, let’s add some properties to the ‘service’ object. Whatever we put on ‘service’ can be directly used inside whichever controller we pass ‘myFactory’ into. We are going to create setArtist and getArtist methods that simply return or set the artist. We are also going to create a method that will call the iTunes API with our created URL. This method is going to return a promise that will fulfill once the data has come back from the iTunes API. If you haven’t had much experience using promises in AngularJS, I highly recommend doing a deep dive on them. Below setArtist accepts an artist and allows you to set the artist. getArtist returns the artist. callItunes first calls makeUrl() in order to build the URL we’ll use with our $http request. Then it sets up a promise object, makes an $http request with our final url, then because $http returns a promise, we are able to call .success or .error after our request. We then resolve our promise with the iTunes data, or we reject it with a message saying ‘There was an error’. app.factory('myFactory', function($http, $q){ var service = {}; var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK' return _finalUrl; } service.setArtist = function(artist){ _artist = artist; } service.getArtist = function(){ return _artist; } service.callItunes = function(){ makeUrl(); var deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }).success(function(data){ deferred.resolve(data); }).error(function(){ deferred.reject('There was an error') }) return deferred.promise; } return service; }); Now our factory is complete. We are now able to inject ‘myFactory’ into any controller and we’ll then be able to call our methods that we attached to our service object (setArtist, getArtist, and callItunes). app.controller('myFactoryCtrl', function($scope, myFactory){ $scope.data = {}; $scope.updateArtist = function(){ myFactory.setArtist($scope.data.artist); }; $scope.submitArtist = function(){ myFactory.callItunes() .then(function(data){ $scope.data.artistData = data; }, function(data){ alert(data); }) } }); In the controller above we’re injecting in the ‘myFactory’ service. We then set properties on our $scope object with data from ‘myFactory’. The only tricky code above is if you’ve never dealt with promises before. Because callItunes is returning a promise, we are able to use the .then() method and only set $scope.data.artistData once our promise is fulfilled with the iTunes data. You’ll notice our controller is very ‘thin’ (This is a good coding practise). All of our logic and persistent data is located in our service, not in our controller. 2) Service Perhaps the biggest thing to know when dealing with creating a Service is that that it’s instantiated with the ‘new’ keyword. For you JavaScript gurus this should give you a big hint into the nature of the code. For those of you with a limited background in JavaScript or for those who aren’t too familiar with what the ‘new’ keyword actually does, let’s review some JavaScript fundamentals that will eventually help us in understanding the nature of a Service. To really see the changes that occur when you invoke a function with the ‘new’ keyword, let’s create a function and invoke it with the ‘new’ keyword, then let’s show what the interpreter does when it sees the ‘new’ keyword. The end results will both be the same. First let’s create our Constructor. var Person = function(name, age){ this.name = name; this.age = age; } This is a typical JavaScript constructor function. Now whenever we invoke the Person function using the ‘new’ keyword, ‘this’ will be bound to the newly created object. Now let’s add a method onto our Person’s prototype so it will be available on every instance of our Person ‘class’. Person.prototype.sayName = function(){ alert(‘My name is ‘ + this.name); } Now, because we put the sayName function on the prototype, every instance of Person will be able to call the sayName function in order alert that instance’s name. Now that we have our Person constructor function and our sayName function on its prototype, let’s actually create an instance of Person then call the sayName function. var tyler = new Person(‘Tyler’, 23); tyler.sayName(); //alerts ‘My name is Tyler’ So all together the code for creating a Person constructor, adding a function to it’s prototype, creating a Person instance, and then calling the function on its prototype looks like this. var Person = function(name, age){ this.name = name; this.age = age; } Person.prototype.sayName = function(){ alert(‘My name is ‘ + this.name); } var tyler = new Person(‘Tyler’, 23); tyler.sayName(); //alerts ‘My name is Tyler’ Now let’s look at what actually is happening when you use the ‘new’ keyword in JavaScript. First thing you should notice is that after using ‘new’ in our example, we’re able to call a method (sayName) on ‘tyler’ just as if it were an object - that’s because it is. So first, we know that our Person constructor is returning an object, whether we can see that in the code or not. Second, we know that because our sayName function is located on the prototype and not directly on the Person instance, the object that the Person function is returning must be delegating to its prototype on failed lookups. In more simple terms, when we call tyler.sayName() the interpreter says “OK, I’m going to look on the ‘tyler’ object we just created, locate the sayName function, then call it. Wait a minute, I don’t see it here - all I see is name and age, let me check the prototype. Yup, looks like it’s on the prototype, let me call it.”. Below is code for how you can think about what the ‘new’ keyword is actually doing in JavaScript. It’s basically a code example of the above paragraph. I’ve put the ‘interpreter view’ or the way the interpreter sees the code inside of notes. var Person = function(name, age){ //The below line creates an object(obj) that will delegate to the person’s prototype on failed lookups. //var obj = Object.create(Person.prototype); //The line directly below this sets ‘this’ to the newly created object //this = obj; this.name = name; this.age = age; //return this; } Now having this knowledge of what the ‘new’ keyword really does in JavaScript, creating a Service in AngularJS should be easier to understand. The biggest thing to understand when creating a Service is knowing that Services are instantiated with the ‘new’ keyword. Combining that knowledge with our examples above, you should now recognize that you’ll be attaching your properties and methods directly to ‘this’ which will then be returned from the Service itself. Let’s take a look at this in action. Unlike what we originally did with the Factory example, we don’t need to create an object then return that object because, like mentioned many times before, we used the ‘new’ keyword so the interpreter will create that object, have it delegate to it’s prototype, then return it for us without us having to do the work. First things first, let’s create our ‘private’ and helper function. This should look very familiar since we did the exact same thing with our factory. I won’t explain what each line does here because I did that in the factory example, if you’re confused, re-read the factory example. app.service('myService', function($http, $q){ var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK' return _finalUrl; } }); Now, we’ll attach all of our methods that will be available in our controller to ‘this’. app.service('myService', function($http, $q){ var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK' return _finalUrl; } this.setArtist = function(artist){ _artist = artist; } this.getArtist = function(){ return _artist; } this.callItunes = function(){ makeUrl(); var deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }).success(function(data){ deferred.resolve(data); }).error(function(){ deferred.reject('There was an error') }) return deferred.promise; } }); Now just like in our factory, setArtist, getArtist, and callItunes will be available in whichever controller we pass myService into. Here’s the myService controller (which is almost exactly the same as our factory controller). app.controller('myServiceCtrl', function($scope, myService){ $scope.data = {}; $scope.updateArtist = function(){ myService.setArtist($scope.data.artist); }; $scope.submitArtist = function(){ myService.callItunes() .then(function(data){ $scope.data.artistData = data; }, function(data){ alert(data); }) } }); Like I mentioned before, once you really understand what ‘new’ does, Services are almost identical to factories in AngularJS. 3) Provider The biggest thing to remember about Providers is that they’re the only service that you can pass into the app.config portion of your application. This is of huge importance if you’re needing to alter some portion of your service object before it’s available everywhere else in your application. Although very similar to Services/Factories, there are a few differences which we’ll discuss. First we set up our Provider in a similar way we did with our Service and Factory. The variables below are our ‘private’ and helper function. app.provider('myProvider', function(){ var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; //Going to set this property on the config function below. this.thingFromConfig = ‘’; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK' return _finalUrl; } } *Again if any portion of the above code is confusing, check out the Factory section where I explain what it all does it greater details. You can think of Providers as having three sections. The first section is the ‘private’ variables/functions that will be modified/set later (shown above). The second section is the variables/functions that will be available in your app.config function and are therefore available to alter before they’re available anywhere else (also shown above). It’s important to note that those variables need to be attached to the ‘this’ keyword. In our example, only ‘thingFromConfig’ will be available to alter in the app.config. The third section (shown below) is all the variables/functions that will be available in your controller when you pass in the ‘myProvider’ service into that specific controller. When creating a service with Provider, the only properties/methods that will be available in your controller are those properties/methods which are returned from the $get() function. The code below puts $get on ‘this’ (which we know will eventually be returned from that function). Now, that $get function returns all the methods/properties we want to be available in the controller. Here’s a code example. this.$get = function($http, $q){ return { callItunes: function(){ makeUrl(); var deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }).success(function(data){ deferred.resolve(data); }).error(function(){ deferred.reject('There was an error') }) return deferred.promise; }, setArtist: function(artist){ _artist = artist; }, getArtist: function(){ return _artist; }, thingOnConfig: this.thingFromConfig } } Now the full Provider code looks like this app.provider('myProvider', function(){ var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; //Going to set this property on the config function below this.thingFromConfig = ''; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK' return _finalUrl; } this.$get = function($http, $q){ return { callItunes: function(){ makeUrl(); var deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }).success(function(data){ deferred.resolve(data); }).error(function(){ deferred.reject('There was an error') }) return deferred.promise; }, setArtist: function(artist){ _artist = artist; }, getArtist: function(){ return _artist; }, thingOnConfig: this.thingFromConfig } } }); Now just like in our factory and Service, setArtist, getArtist, and callItunes will be available in whichever controller we pass myProvider into. Here’s the myProvider controller (which is almost exactly the same as our factory/Service controller). app.controller('myProviderCtrl', function($scope, myProvider){ $scope.data = {}; $scope.updateArtist = function(){ myProvider.setArtist($scope.data.artist); }; $scope.submitArtist = function(){ myProvider.callItunes() .then(function(data){ $scope.data.artistData = data; }, function(data){ alert(data); }) } $scope.data.thingFromConfig = myProvider.thingOnConfig; }); As mentioned before, the whole point of creating a service with Provider is to be able to alter some variables through the app.config function before the final object is passed to the rest of the application. Let’s see an example of that. app.config(function(myProviderProvider){ //Providers are the only service you can pass into app.config myProviderProvider.thingFromConfig = 'This sentence was set in app.config. Providers are the only service that can be passed into config. Check out the code to see how it works'; }); Now you can see how ‘thingFromConfig’ is as empty string in our provider, but when that shows up in the DOM, it will be ‘This sentence was set…’.
All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type. The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services. The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types — Value, Factory, Service and Constant — are just syntactic sugar on top of a provider recipe. The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector. The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function. The Provider recipe is usually overkill. It adds one more layer of indirection by allowing you to configure the creation of the factory. You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications. The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator. See the provider documentation.
Understanding AngularJS Factory, Service and Provider All of these are used to share reusable singleton objects. It helps to share reusable code across your app/various components/modules. From Docs Service/Factory: Lazily instantiated – Angular only instantiates a service/factory when an application component depends on it. Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory. Factory A factory is function where you can manipulate/add logic before creating an object, then the newly created object gets returned. app.factory('MyFactory', function() { var serviceObj = {}; //creating an object with methods/functions or variables serviceObj.myFunction = function() { //TO DO: }; //return that object return serviceObj; }); Usage It can be just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are injecting it inside your controller/factory/directive functions. It is instantiated only once per app. Service Simply while looking at the services think about the array prototype. A service is a function which instantiates a new object using the 'new' keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains methods/properties). app.service('MyService', function() { //directly binding events to this context this.myServiceFunction = function() { //TO DO: }; }); Usage Use it when you need to share a single object throughout the application. For example, authenticated user details, share-able methods/data, Utility functions etc. Provider A provider is used to create a configurable service object. You can configure the service setting from config function. It returns a value by using the $get() function. The $get function gets executed on the run phase in angular. app.provider('configurableService', function() { var name = ''; //this method can be be available at configuration time inside app.config. this.setName = function(newName) { name = newName; }; this.$get = function() { var getName = function() { return name; }; return { getName: getName //exposed object to where it gets injected. }; }; }); Usage When you need to provide module-wise configuration for your service object before making it available, eg. suppose you want to set your API URL on basis of your Environment like dev, stage or prod NOTE Only provider will be available in config phase of angular, while service & factory are not. Hope this has cleared up your understanding about Factory, Service and Provider.
For me, the revelation came when I realized that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through dependency injection. Say we have: app.factory('a', fn); app.service('b', fn); app.provider('c', fn); The difference between the three is that: a's stored value comes from running fn. b’s stored value comes from newing fn. c’s stored value comes from first getting an instance by newing fn, and then running a $get method of the instance. Which means there’s something like a cache object inside AngularJS, whose value of each injection is only assigned once, when they've been injected the first time, and where: cache.a = fn() cache.b = new fn() cache.c = (new fn()).$get() This is why we use this in services, and define a this.$get in providers.
Service vs provider vs factory: I am trying to keep it simple. It's all about basic JavaScript concept. First of all, let's talk about services in AngularJS! What is Service: In AngularJS, Service is nothing but a singleton JavaScript object which can store some useful methods or properties. This singleton object is created per ngApp(Angular app) basis and it is shared among all the controllers within current app. When Angularjs instantiate a service object, it register this service object with a unique service name. So each time when we need service instance, Angular search the registry for this service name, and it returns the reference to service object. Such that we can invoke method, access properties etc on the service object. You may have question whether you can also put properties, methods on scope object of controllers! So why you need service object? Answers is: services are shared among multiple controller scope. If you put some properties/methods in a controller's scope object , it will be available to current scope only. But when you define methods, properties on service object, it will be available globally and can be accessed in any controller's scope by injecting that service. So if there are three controller scope, let it be controllerA, controllerB and controllerC, all will share same service instance. <div ng-controller='controllerA'> <!-- controllerA scope --> </div> <div ng-controller='controllerB'> <!-- controllerB scope --> </div> <div ng-controller='controllerC'> <!-- controllerC scope --> </div> How to create a service? AngularJS provide different methods to register a service. Here we will concentrate on three methods factory(..),service(..),provider(..); Use this link for code reference Factory function: We can define a factory function as below. factory('serviceName',function fnFactory(){ return serviceInstance;}) AngularJS provides 'factory('serviceName', fnFactory)' method which takes two parameter, serviceName and a JavaScript function. Angular creates service instance by invoking the function fnFactory() such as below. var serviceInstace = fnFactory(); The passed function can define a object and return that object. AngularJS simply stores this object reference to a variable which is passed as first argument. Anything which is returned from fnFactory will be bound to serviceInstance . Instead of returning object , we can also return function, values etc, Whatever we will return , will be available to service instance. Example: var app= angular.module('myApp', []); //creating service using factory method app.factory('factoryPattern',function(){ var data={ 'firstName':'Tom', 'lastName':' Cruise', greet: function(){ console.log('hello!' + this.firstName + this.lastName); } }; //Now all the properties and methods of data object will be available in our service object return data; }); Service Function: service('serviceName',function fnServiceConstructor(){}) It's the another way, we can register a service. The only difference is the way AngularJS tries to instantiate the service object. This time angular uses 'new' keyword and call the constructor function something like below. var serviceInstance = new fnServiceConstructor(); In the constructor function we can use 'this' keyword for adding properties/methods to the service object. example: //Creating a service using the service method var app= angular.module('myApp', []); app.service('servicePattern',function(){ this.firstName ='James'; this.lastName =' Bond'; this.greet = function(){ console.log('My Name is '+ this.firstName + this.lastName); }; }); Provider function: Provider() function is the another way for creating services. Let we are interested to create a service which just display some greeting message to the user. But we also want to provide a functionality such that user can set their own greeting message. In technical terms we want to create configurable services. How can we do this ? There must be a way, so that app could pass their custom greeting messages and Angularjs would make it available to factory/constructor function which create our services instance. In such a case provider() function do the job. using provider() function we can create configurable services. We can create configurable services using provider syntax as given below. /*step1:define a service */ app.provider('service',function serviceProviderConstructor(){}); /*step2:configure the service */ app.config(function configureService(serviceProvider){}); How does provider syntax internally work? 1.Provider object is created using constructor function we defined in our provider function. var serviceProvider = new serviceProviderConstructor(); 2.The function we passed in app.config(), get executed. This is called config phase, and here we have a chance to customize our service. configureService(serviceProvider); 3.Finally service instance is created by calling $get method of serviceProvider. serviceInstance = serviceProvider.$get() Sample code for creating service using provide syntax: var app= angular.module('myApp', []); app.provider('providerPattern',function providerConstructor(){ //this function works as constructor function for provider this.firstName = 'Arnold '; this.lastName = ' Schwarzenegger' ; this.greetMessage = ' Welcome, This is default Greeting Message' ; //adding some method which we can call in app.config() function this.setGreetMsg = function(msg){ if(msg){ this.greetMessage = msg ; } }; //We can also add a method which can change firstName and lastName this.$get = function(){ var firstName = this.firstName; var lastName = this.lastName ; var greetMessage = this.greetMessage; var data={ greet: function(){ console.log('hello, ' + firstName + lastName+'! '+ greetMessage); } }; return data ; }; }); app.config( function(providerPatternProvider){ providerPatternProvider.setGreetMsg(' How do you do ?'); } ); Working Demo Summary: Factory use a factory function which return a service instance. serviceInstance = fnFactory(); Service use a constructor function and Angular invoke this constructor function using 'new' keyword for creating the service instance. serviceInstance = new fnServiceConstructor(); Provider defines a providerConstructor function, this providerConstructor function defines a factory function $get . Angular calls $get() to create the service object. Provider syntax has an added advantage of configuring the service object before it get instantiated. serviceInstance = $get();
As pointed out by several people here correctly a factory, provider, service, and even value and constant are versions of the same thing. You can dissect the more general provider into all of them. Like so: Here's the article this image is from: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
Factory You give AngularJS a function, AngularJS will cache and inject the return value when the factory is requested. Example: app.factory('factory', function() { var name = ''; // Return value **is** the object that will be injected return { name: name; } }) Usage: app.controller('ctrl', function($scope, factory) { $scope.name = factory.name; }); Service You give AngularJS a function, AngularJS will call new to instantiate it. It is the instance that AngularJS creates that will be cached and injected when the service is requested. Since new was used to instantiate the service, the keyword this is valid and refers to the instance. Example: app.service('service', function() { var name = ''; this.setName = function(newName) { name = newName; } this.getName = function() { return name; } }); Usage: app.controller('ctrl', function($scope, service) { $scope.name = service.getName(); }); Provider You give AngularJS a function, and AngularJS will call its $get function. It is the return value from the $get function that will be cached and injected when the service is requested. Providers allow you to configure the provider before AngularJS calls the $get method to get the injectible. Example: app.provider('provider', function() { var name = ''; this.setName = function(newName) { name = newName; } this.$get = function() { return { name: name } } }) Usage (as an injectable in a controller) app.controller('ctrl', function($scope, provider) { $scope.name = provider.name; }); Usage (configuring the provider before $get is called to create the injectable) app.config(function(providerProvider) { providerProvider.setName('John'); });
I noticed something interesting when playing around with providers. Visibility of injectables is different for providers than it is for services and factories. If you declare an AngularJS "constant" (for example, myApp.constant('a', 'Robert');), you can inject it into services, factories, and providers. But if you declare an AngularJS "value" (for example., myApp.value('b', {name: 'Jones'});), you can inject it into services and factories, but NOT into the provider-creating function. You can, however, inject it into the $get function that you define for your provider. This is mentioned in the AngularJS documentation, but it's easy to miss. You can find it on the %provide page in the sections on the value and constant methods. http://jsfiddle.net/R2Frv/1/ <div ng-app="MyAppName"> <div ng-controller="MyCtrl"> <p>from Service: {{servGreet}}</p> <p>from Provider: {{provGreet}}</p> </div> </div> <script> var myApp = angular.module('MyAppName', []); myApp.constant('a', 'Robert'); myApp.value('b', {name: 'Jones'}); myApp.service('greetService', function(a,b) { this.greeter = 'Hi there, ' + a + ' ' + b.name; }); myApp.provider('greetProvider', function(a) { this.firstName = a; this.$get = function(b) { this.lastName = b.name; this.fullName = this.firstName + ' ' + this.lastName; return this; }; }); function MyCtrl($scope, greetService, greetProvider) { $scope.servGreet = greetService.greeter; $scope.provGreet = greetProvider.fullName; } </script>
This is very confusing part for newbie and I have tried to clarify it in easy words AngularJS Service: is used for sharing utility functions with the service reference in the controller. Service is singleton in nature so for one service only one instance is created in the browser and the same reference is used throughout the page. In the service, we create function names as property with this object. AngularJS Factory: the purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object. AngularJS Provider: the purpose of this is again same however Provider gives the output of it's $get function. Defining and using Service, Factory and Provider are explained at http://www.dotnetfunda.com/articles/show/3156/difference-between-angularjs-service-factory-and-provider
For me the best and the simplest way of understanding the difference is: var service, factory; service = factory = function(injection) {} How AngularJS instantiates particular components (simplified): // service var angularService = new service(injection); // factory var angularFactory = factory(injection); So, for the service, what becomes the AngularJS component is the object instance of the class which is represented by service declaration function. For the factory, it is the result returned from the factory declaration function. The factory may behave the same as the service: var factoryAsService = function(injection) { return new function(injection) { // Service content } } The simplest way of thinking is the following one: Service is an singleton object instance. Use services if you want to provide a singleton object for your code. Factory is a class. Use factories if you want to provide custom classes for your code (can't be done with services because they are already instantiated). The factory 'class' example is provided in the comments around, as well as provider difference.
My clarification on this matter: Basically all of the mentioned types (service, factory, provider, etc.) are just creating and configuring global variables (that are of course global to the entire application), just as old fashioned global variables were. While global variables are not recommended, the real usage of these global variables is to provide dependency injection, by passing the variable to the relevant controller. There are many levels of complications in creating the values for the "global variables": Constant This defines an actual constant that should not be modified during the entire application, just like constants in other languages are (something that JavaScript lacks). Value This is a modifiable value or object, and it serves as some global variable, that can even be injected when creating other services or factories (see further on these). However, it must be a "literal value", which means that one has to write out the actual value, and cannot use any computation or programming logic (in other words 39 or myText or {prop: "value"} are OK, but 2 +2 is not). Factory A more general value, that is possible to be computed right away. It works by passing a function to AngularJS with the logic needed to compute the value and AngularJS executes it, and it saves the return value in the named variable. Note that it is possible to return a object (in which case it will function similar to a service) or a function (that will be saved in the variable as a callback function). Service A service is a more stripped-down version of factory which is valid only when the value is an object, and it allows for writing any logic directly in the function (as if it would be a constructor), as well as declaring and accessing the object properties using the this keyword. Provider Unlike a service which is a simplified version of factory, a provider is a more complex, but more flexible way of initializing the "global" variables, with the biggest flexibility being the option to set values from the app.config. It works like using a combination of service and provider, by passing to provider a function that has properties declared using the this keyword, which can be used from the app.config. Then it needs to have a separate $.get function which is executed by AngularJS after setting the above properties via the app.config file , and this $.get function behaves just as the factory above, in that its return value is used to initialize the "global" variables.
My understanding is very simple below. Factory: You simply create an object inside of the factory and return it. Service: You just have a standard function that uses this keyword to define a function. Provider: There is a $get object that you define and it can be used to get the object that returns data.
Summary from Angular docs: There are five recipe types that define how to create objects: Value, Factory, Service, Provider and Constant. Factory and Service are the most commonly used recipes. The only difference between them is that the Service recipe works better for objects of a custom type, while the Factory can produce JavaScript primitives and functions. The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it. Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration. Best answers from SO: https://stackoverflow.com/a/26924234/165673 (<-- GOOD) https://stackoverflow.com/a/27263882/165673 https://stackoverflow.com/a/16566144/165673
All the good answers already. I would like to add few more points on Service and Factory. Along with the difference between service/factory. And one can also have questions like: Should I use service or factory? What’s the difference? Is they do same or have same behaviour? Lets start with the difference between Service and factory: Both are Singletons: Whenever Angular find these as a dependency first time,it create a single instance of service/factory. Once the instance is created, same instance is used forever. Can be used to model an object with behavior: They can both have methods, internal state variables, and so on. Though the way you write that code will differ. Services: A service is a constructor function, and Angular will instantiate it by calling new yourServiceName(). This means a couple of things. Functions and instance variables will be properties of this. You don’t need to return a value. When Angular calls new yourServiceName(), it’ll receive the this object with all the properties you put on it. Sample Example: angular.service('MyService', function() { this.aServiceVariable = "Ved Prakash" this.aServiceMethod = function() { return //code }; }); When Angular injects this MyService service into a controller that depends on it, that controller will get a MyService that it can call functions on, e.g. MyService.aServiceMethod (). Be careful with this: Since the constructed service is an object, the methods inside it can refer to this when they’re called: angular.service('ScoreKeeper', function($http) { this.score = 0; this.getScore = function() { return this.score; }; this.setScore = function(newScore) { this.score = newScore; }; this.addOne = function() { this.score++; }; }); You might be tempted to call ScoreKeeper.setScore in a promise chain, for instance if you initialized the score by grabbing it from the server: $http.get('/score').then(ScoreKeeper.setScore). The trouble with this is that ScoreKeeper.setScore will be called with this bound to null and you’ll get errors. The better way would be $http.get('/score').then(ScoreKeeper.setScore.bind(ScoreKeeper)). Whether you choose to use this in your service methods or not, be careful how you call them. Returning a Value from a Service: Due to how JavaScript constructors work, if you return a complex value (i.e., an Object) from a constructor function, the caller will get that Object instead of the this instance. This means that you can basically copy-paste the factory example from below, replace factory with service, and it’ll work: angular.service('MyService', function($http) { var api = {}; api.aServiceMethod= function() { return $http.get('/users'); }; return api; }); So when Angular constructs your service with new MyService(), it’ll get that api object instead of the MyService instance. This is the behavior for any complex values (objects, functions) but not for primitive types. Factories: A factory is a plain old function that returns a value. The return value is what gets injected into things that depend on the factory. A typical factory pattern in Angular is to return an object with functions as properties, like this: angular.factory('MyFactory', function($http) { var api = {}; api.aFactoryMethod= function() { return $http.get('/users'); }; return api; }); The injected value for a factory dependency is the factory’s return value, and it doesn’t have to be an object. It could be a function Answers for above 1 and 2 questions: For the most part, just stick with using factories for everything. Their behavior is easier to understand. There’s no choice to make about whether to return a value or not, and furthermore, no bugs to be introduced if you do the wrong thing. I still refer to them as “services” when I’m talking about injecting them as dependencies, though. Service/Factory behavior is very similar, and some people will say that either one is fine. That’s somewhat true, but I find it easier to follow the advice of John Papa’s style guide and just stick with factories.**
An additional clarification is that factories can create functions/primitives, while services cannot. Check out this jsFiddle based on Epokk's: http://jsfiddle.net/skeller88/PxdSP/1351/. The factory returns a function that can be invoked: myApp.factory('helloWorldFromFactory', function() { return function() { return "Hello, World!"; }; }); The factory can also return an object with a method that can be invoked: myApp.factory('helloWorldFromFactory', function() { return { sayHello: function() { return "Hello, World!"; } }; }); The service returns an object with a method that can be invoked: myApp.service('helloWorldFromService', function() { this.sayHello = function() { return "Hello, World!"; }; }); For more details, see a post I wrote on the difference: http://www.shanemkeller.com/tldr-services-vs-factories-in-angular/
There are good answers already, but I just want to share this one. First of all: Provider is the way/recipe to create a service (singleton object) that suppose to be injected by $injector (how AngulaJS goes about IoC pattern). And Value, Factory, Service and Constant (4 ways) - the syntactic sugar over Provider way/recepie. There is Service vs Factory part has been covered: https://www.youtube.com/watch?v=BLzNCkPn3ao Service is all about new keyword actually which as we know does 4 things: creates brand new object links it to its prototype object connects context to this and returns this And Factory is all about Factory Pattern - contains functions that return Objects like that Service. ability to use other services (have dependencies) service initialization delayed/lazy initialization And this simple/short video: covers also Provider: https://www.youtube.com/watch?v=HvTZbQ_hUZY (there you see can see how they go from factory to provider) Provider recipe is used mostly in the app config, before the app has fully started/initialized.
After reading all these post It created more confuse for me.. But still all is worthfull information.. finally I found following table which will give information with simple comparision The injector uses recipes to create two types of objects: services and special purpose objects There are five recipe types that define how to create objects: Value, Factory, Service, Provider and Constant. Factory and Service are the most commonly used recipes. The only difference between them is that the Service recipe works better for objects of a custom type, while the Factory can produce JavaScript primitives and functions. The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it. Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration. All special purpose objects except for the Controller are defined via Factory recipes. And for beginner understand:- This may not correct use case but in high level this is what usecase for these three. If you want to use in angular module config function should created as provider angular.module('myApp').config(function($testProvider){ $testProvider.someFunction(); }) Ajax call or third party integrations needs to be service. For Data manipulations create it as factory For basic scenarios factory&Service behaves same.
Here is some broilerplate code I've come up with as a code-template for object factory in AngularjS. I've used a Car/CarFactory as an example to illustrate. Makes for simple implementation code in the controller. <script> angular.module('app', []) .factory('CarFactory', function() { /** * BroilerPlate Object Instance Factory Definition / Example */ this.Car = function() { // initialize instance properties angular.extend(this, { color : null, numberOfDoors : null, hasFancyRadio : null, hasLeatherSeats : null }); // generic setter (with optional default value) this.set = function(key, value, defaultValue, allowUndefined) { // by default, if (typeof allowUndefined === 'undefined') { // we don't allow setter to accept "undefined" as a value allowUndefined = false; } // if we do not allow undefined values, and.. if (!allowUndefined) { // if an undefined value was passed in if (value === undefined) { // and a default value was specified if (defaultValue !== undefined) { // use the specified default value value = defaultValue; } else { // otherwise use the class.prototype.defaults value value = this.defaults[key]; } // end if/else } // end if } // end if // update this[key] = value; // return reference to this object (fluent) return this; }; // end this.set() }; // end this.Car class definition // instance properties default values this.Car.prototype.defaults = { color: 'yellow', numberOfDoors: 2, hasLeatherSeats: null, hasFancyRadio: false }; // instance factory method / constructor this.Car.prototype.instance = function(params) { return new this.constructor() .set('color', params.color) .set('numberOfDoors', params.numberOfDoors) .set('hasFancyRadio', params.hasFancyRadio) .set('hasLeatherSeats', params.hasLeatherSeats) ; }; return new this.Car(); }) // end Factory Definition .controller('testCtrl', function($scope, CarFactory) { window.testCtrl = $scope; // first car, is red, uses class default for: // numberOfDoors, and hasLeatherSeats $scope.car1 = CarFactory .instance({ color: 'red' }) ; // second car, is blue, has 3 doors, // uses class default for hasLeatherSeats $scope.car2 = CarFactory .instance({ color: 'blue', numberOfDoors: 3 }) ; // third car, has 4 doors, uses class default for // color and hasLeatherSeats $scope.car3 = CarFactory .instance({ numberOfDoors: 4 }) ; // sets an undefined variable for 'hasFancyRadio', // explicitly defines "true" as default when value is undefined $scope.hasFancyRadio = undefined; $scope.car3.set('hasFancyRadio', $scope.hasFancyRadio, true); // fourth car, purple, 4 doors, // uses class default for hasLeatherSeats $scope.car4 = CarFactory .instance({ color: 'purple', numberOfDoors: 4 }); // and then explicitly sets hasLeatherSeats to undefined $scope.hasLeatherSeats = undefined; $scope.car4.set('hasLeatherSeats', $scope.hasLeatherSeats, undefined, true); // in console, type window.testCtrl to see the resulting objects }); </script> Here is a simpler example. I'm using a few third party libraries that expect a "Position" object exposing latitude and longitude, but via different object properties. I didn't want to hack the vendor code, so I adjusted the "Position" objects I was passing around. angular.module('app') .factory('PositionFactory', function() { /** * BroilerPlate Object Instance Factory Definition / Example */ this.Position = function() { // initialize instance properties // (multiple properties to satisfy multiple external interface contracts) angular.extend(this, { lat : null, lon : null, latitude : null, longitude : null, coords: { latitude: null, longitude: null } }); this.setLatitude = function(latitude) { this.latitude = latitude; this.lat = latitude; this.coords.latitude = latitude; return this; }; this.setLongitude = function(longitude) { this.longitude = longitude; this.lon = longitude; this.coords.longitude = longitude; return this; }; }; // end class definition // instance factory method / constructor this.Position.prototype.instance = function(params) { return new this.constructor() .setLatitude(params.latitude) .setLongitude(params.longitude) ; }; return new this.Position(); }) // end Factory Definition .controller('testCtrl', function($scope, PositionFactory) { $scope.position1 = PositionFactory.instance({latitude: 39, longitude: 42.3123}); $scope.position2 = PositionFactory.instance({latitude: 39, longitude: 42.3333}); }) // end controller ;
Using as reference this page and the documentation (which seems to have greatly improved since the last time I looked), I put together the following real(-ish) world demo which uses 4 of the 5 flavours of provider; Value, Constant, Factory and full blown Provider. HTML: <div ng-controller="mainCtrl as main"> <h1>{{main.title}}*</h1> <h2>{{main.strapline}}</h2> <p>Earn {{main.earn}} per click</p> <p>You've earned {{main.earned}} by clicking!</p> <button ng-click="main.handleClick()">Click me to earn</button> <small>* Not actual money</small> </div> app var app = angular.module('angularProviders', []); // A CONSTANT is not going to change app.constant('range', 100); // A VALUE could change, but probably / typically doesn't app.value('title', 'Earn money by clicking'); app.value('strapline', 'Adventures in ng Providers'); // A simple FACTORY allows us to compute a value # runtime. // Furthermore, it can have other dependencies injected into it such // as our range constant. app.factory('random', function randomFactory(range) { // Get a random number within the range defined in our CONSTANT return Math.random() * range; }); // A PROVIDER, must return a custom type which implements the functionality // provided by our service (see what I did there?). // Here we define the constructor for the custom type the PROVIDER below will // instantiate and return. var Money = function(locale) { // Depending on locale string set during config phase, we'll // use different symbols and positioning for any values we // need to display as currency this.settings = { uk: { front: true, currency: '£', thousand: ',', decimal: '.' }, eu: { front: false, currency: '€', thousand: '.', decimal: ',' } }; this.locale = locale; }; // Return a monetary value with currency symbol and placement, and decimal // and thousand delimiters according to the locale set in the config phase. Money.prototype.convertValue = function(value) { var settings = this.settings[this.locale], decimalIndex, converted; converted = this.addThousandSeparator(value.toFixed(2), settings.thousand); decimalIndex = converted.length - 3; converted = converted.substr(0, decimalIndex) + settings.decimal + converted.substr(decimalIndex + 1); converted = settings.front ? settings.currency + converted : converted + settings.currency; return converted; }; // Add supplied thousand separator to supplied value Money.prototype.addThousandSeparator = function(value, symbol) { return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, symbol); }; // PROVIDER is the core recipe type - VALUE, CONSTANT, SERVICE & FACTORY // are all effectively syntactic sugar built on top of the PROVIDER construct // One of the advantages of the PROVIDER is that we can configure it before the // application starts (see config below). app.provider('money', function MoneyProvider() { var locale; // Function called by the config to set up the provider this.setLocale = function(value) { locale = value; }; // All providers need to implement a $get method which returns // an instance of the custom class which constitutes the service this.$get = function moneyFactory() { return new Money(locale); }; }); // We can configure a PROVIDER on application initialisation. app.config(['moneyProvider', function(moneyProvider) { moneyProvider.setLocale('uk'); //moneyProvider.setLocale('eu'); }]); // The ubiquitous controller app.controller('mainCtrl', function($scope, title, strapline, random, money) { // Plain old VALUE(s) this.title = title; this.strapline = strapline; this.count = 0; // Compute values using our money provider this.earn = money.convertValue(random); // random is computed # runtime this.earned = money.convertValue(0); this.handleClick = function() { this.count ++; this.earned = money.convertValue(random * this.count); }; }); Working demo.
This answer address the topic/question how Factory, Service and Constant — are just syntactic sugar on top of a provider recipe? OR how factory ,servic and providers are simailar internally basically what happens is When you make a factory() it sets you function provided in second argument to provider's $get and return it(provider(name, {$get:factoryFn })), all you get is provider but there is no property/method other than $get of that provider(means you can't configure this) Source code of factory function factory(name, factoryFn, enforce) { return provider(name, { $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn }); }; When making a service() it return you providing a factory() with a function that injects the constructor (return the instance of the constructor you provided in your service) and returns it Source code of service function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); }; So basically in both cases you eventually get a providers $get set to your function you provided , but you can give anything extra than $get as you can originally provide in provider() for config block
I know a lot of excellent answer but I have to share my experience of using 1. service for most cases of default 2. factory used to create the service that specific instance // factory.js //////////////////////////// (function() { 'use strict'; angular .module('myApp.services') .factory('xFactory', xFactoryImp); xFactoryImp.$inject = ['$http']; function xFactoryImp($http) { var fac = function (params) { this._params = params; // used for query params }; fac.prototype.nextPage = function () { var url = "/_prc"; $http.get(url, {params: this._params}).success(function(data){ ... } return fac; } })(); // service.js ////////////////////////// (function() { 'use strict'; angular .module('myApp.services') .service('xService', xServiceImp); xServiceImp.$inject = ['$http']; function xServiceImp($http) { this._params = {'model': 'account','mode': 'list'}; this.nextPage = function () { var url = "/_prc"; $http.get(url, {params: this._params}).success(function(data){ ... } } })(); and using: controller: ['xFactory', 'xService', function(xFactory, xService){ // books = new instance of xFactory for query 'book' model var books = new xFactory({'model': 'book', 'mode': 'list'}); // accounts = new instance of xFactory for query 'accounts' model var accounts = new xFactory({'model': 'account', 'mode': 'list'}); // accounts2 = accounts variable var accounts2 = xService; ...
Little late to the party. But I thought this is more helpful for who would like to learn (or have clarity) on developing Angular JS Custom Services using factory, service and provider methodologies. I came across this video which explains clearly about factory, service and provider methodologies for developing AngularJS Custom Services: https://www.youtube.com/watch?v=oUXku28ex-M Source Code: http://www.techcbt.com/Post/353/Angular-JS-basics/how-to-develop-angularjs-custom-service Code posted here is copied straight from the above source, to benefit readers. The code for "factory" based custom service is as follows (which goes with both sync and async versions along with calling http service): var app = angular.module("app", []); app.controller('emp', ['$scope', 'calcFactory', function($scope, calcFactory) { $scope.a = 10; $scope.b = 20; $scope.doSum = function() { //$scope.sum = calcFactory.getSum($scope.a, $scope.b); //synchronous calcFactory.getSum($scope.a, $scope.b, function(r) { //aynchronous $scope.sum = r; }); }; } ]); app.factory('calcFactory', ['$http', '$log', function($http, $log) { $log.log("instantiating calcFactory.."); var oCalcService = {}; //oCalcService.getSum = function(a,b){ // return parseInt(a) + parseInt(b); //}; //oCalcService.getSum = function(a, b, cb){ // var s = parseInt(a) + parseInt(b); // cb(s); //}; oCalcService.getSum = function(a, b, cb) { //using http service $http({ url: 'http://localhost:4467/Sum?a=' + a + '&b=' + b, method: 'GET' }).then(function(resp) { $log.log(resp.data); cb(resp.data); }, function(resp) { $log.error("ERROR occurred"); }); }; return oCalcService; } ]); The code for "service" methodology for Custom Services (this is pretty similar to 'factory', but different from syntax point of view): var app = angular.module("app", []); app.controller('emp', ['$scope', 'calcService', function($scope, calcService){ $scope.a = 10; $scope.b = 20; $scope.doSum = function(){ //$scope.sum = calcService.getSum($scope.a, $scope.b); calcService.getSum($scope.a, $scope.b, function(r){ $scope.sum = r; }); }; }]); app.service('calcService', ['$http', '$log', function($http, $log){ $log.log("instantiating calcService.."); //this.getSum = function(a,b){ // return parseInt(a) + parseInt(b); //}; //this.getSum = function(a, b, cb){ // var s = parseInt(a) + parseInt(b); // cb(s); //}; this.getSum = function(a, b, cb){ $http({ url: 'http://localhost:4467/Sum?a=' + a + '&b=' + b, method: 'GET' }).then(function(resp){ $log.log(resp.data); cb(resp.data); },function(resp){ $log.error("ERROR occurred"); }); }; }]); The code for "provider" methodology for Custom Services (this is necessary, if you would like to develop service which could be configured): var app = angular.module("app", []); app.controller('emp', ['$scope', 'calcService', function($scope, calcService){ $scope.a = 10; $scope.b = 20; $scope.doSum = function(){ //$scope.sum = calcService.getSum($scope.a, $scope.b); calcService.getSum($scope.a, $scope.b, function(r){ $scope.sum = r; }); }; }]); app.provider('calcService', function(){ var baseUrl = ''; this.config = function(url){ baseUrl = url; }; this.$get = ['$log', '$http', function($log, $http){ $log.log("instantiating calcService...") var oCalcService = {}; //oCalcService.getSum = function(a,b){ // return parseInt(a) + parseInt(b); //}; //oCalcService.getSum = function(a, b, cb){ // var s = parseInt(a) + parseInt(b); // cb(s); //}; oCalcService.getSum = function(a, b, cb){ $http({ url: baseUrl + '/Sum?a=' + a + '&b=' + b, method: 'GET' }).then(function(resp){ $log.log(resp.data); cb(resp.data); },function(resp){ $log.error("ERROR occurred"); }); }; return oCalcService; }]; }); app.config(['calcServiceProvider', function(calcServiceProvider){ calcServiceProvider.config("http://localhost:4467"); }]); Finally the UI which works with any of the above services: <html> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" ></script> <script type="text/javascript" src="t03.js"></script> </head> <body ng-app="app"> <div ng-controller="emp"> <div> Value of a is {{a}}, but you can change <input type=text ng-model="a" /> <br> Value of b is {{b}}, but you can change <input type=text ng-model="b" /> <br> </div> Sum = {{sum}}<br> <button ng-click="doSum()">Calculate</button> </div> </body> </html>
Just to clarify things, from the AngularJS source, you can see a service just calls the factory function which in turn calls the provider function: function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); }
Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course) SERVICE: Syntax: app.js var app = angular.module('ServiceExample',[]); var serviceExampleController = app.controller('ServiceExampleController', ServiceExampleController); var serviceExample = app.service('NameOfTheService', NameOfTheService); ServiceExampleController.$inject = ['NameOfTheService'] //protects from minification of js files function ServiceExampleController(NameOfTheService){ serviceExampleController = this; serviceExampleController.data = NameOfTheService.getSomeData(); } function NameOfTheService(){ nameOfTheService = this; nameOfTheService.data = "Some Data"; nameOfTheService.getSomeData = function(){ return nameOfTheService.data; } } index.html <div ng-controller = "ServiceExampleController as serviceExample"> {{serviceExample.data}} </div> Features of Service: Lazily Instantiated: If it is not injected it won't be instantiated ever. So to use it will have to inject it to a module. Singleton: If injected to multiple modules, all will have access to only one particular instance. That is why very convenient to share data across different controllers. FACTORY First let's have a look at the syntax: app.js: var app = angular.module('FactoryExample',[]); var factoryController = app.controller('FactoryController', FactoryController); var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne); var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo); //first implementation where it returns a function function NameOfTheFactoryOne(){ var factory = function(){ return new SomeService(); } return factory; } //second implementation where an object literal would be returned function NameOfTheFactoryTwo(){ var factory = { getSomeService : function(){ return new SomeService(); } }; return factory; } Now using the above two in the controller: var factoryOne = NameOfTheFactoryOne() //since it returns a function factoryOne.someMethod(); var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object factoryTwo.someMethod(); Features of Factory: Follows the factory design pattern. The factory is a central place that produces new objects or functions. Not only produces singleton, but customizable services. The .service() method is a factory that always produces the same type of service, which is a singleton, and without any easy way to configure it's behavior. That .service() method is usually used as a shortcut for something that doesn't require any configuration whatsoever. PROVIDER Let's again have a look at the Syntax first: angular.module('ProviderModule', []) .controller('ProviderModuleController', ProviderModuleController) .provider('ServiceProvider', ServiceProvider) .config(Config); //optional Config.$inject = ['ServiceProvider']; function Config(ServiceProvider) { ServiceProvider.defaults.maxItems = 10; //some default value } ProviderModuleController.$inject = ['ServiceProvider']; function ProviderModuleController(ServiceProvider) { //some methods } function ServiceProvider() { var provider = this; provider.defaults = { maxItems: 10 }; provider.$get = function () { var someList = new someListService(provider.defaults.maxItems); return someList; }; } } Features of Provider: Provider is the most flexible method of creating services in Angular. Not only we can create a factory that's dynamically configurable, but at the time of using the factory, with the provider method, we could custom configure the factory just once at the bootstrapping of our entire application. The factory can then be used throughout the application with custom settings. In other words, we can configure this factory before the application starts. In fact in the angular documentation it is mentioned that the provider method is what actually gets executed behind the scenes when we configure our services with either .service or .factory methods. The $get is a function that is directly attached to the provider instance. That function is a factory function. In other words, it's just like the one that we use to provide to the .factory method. In that function, we create our own service. This $get property, that's a function, is what makes the provider a provider. AngularJS expects the provider to have a $get property whose value is a function that Angular will treat as a factory function. But what makes this whole provider setup very special, is the fact that we can provide some config object inside the service provider, and that usually comes with defaults that we can later overwrite in the step, where we can configure the entire application.
Essentially, Provider, Factory, and Service are all Services. A Factory is a special case of a Service when all you need is a $get() function, allowing you to write it with less code. The major differences among Services, Factories, and Providers are their complexities. Services are the simplest form, Factories are a little more robust, and Providers are configurable at runtime. Here is a summary of when to use each: Factory: The value you are providing needs to be calculated based on other data. Service: You are returning an object with methods. Provider: You want to be able to configure, during the config phase, the object that is going to be created before it’s created. Use the Provider mostly in the app config, before the app has fully initialized.
Factory: The factory you actually create an object inside of the factory and return it. service: The service you just have a standard function that uses the this keyword to define function. provider: The provider there’s a $get you define and it can be used to get the object that returns the data.
1.Services are singleton objects that are created when necessary and are never cleaned up until the end of the application life-cycle (when the browser is closed). Controllers are destroyed and cleaned up when they are no longer needed. 2.The easiest way to create a service is by using the factory() method. The factory() method allows us to define a service by returning an object that contains service functions and service data. The service definition function is where we place our injectable services, such as $http and $q. Ex: angular.module('myApp.services') .factory('User', function($http) { // injectables go here var backendUrl = "http://localhost:3000"; var service = { // our factory definition user: {}, setName: function(newName) { service.user['name'] = newName; }, setEmail: function(newEmail) { service.user['email'] = newEmail; }, save: function() { return $http.post(backendUrl + '/users', { user: service.user }); } }; return service; }); Using the factory() in our app It’s easy to use the factory in our application as we can simply inject it where we need it at run-time. angular.module('myApp') .controller('MainController', function($scope, User) { $scope.saveUser = User.save; }); The service() method, on the other hand allows us to create a service by defining a constructor function. We can use a prototypical object to define our service, instead of a raw javascript object. Similar to the factory() method, we’ll also set the injectables in the function definition. The lowest level way to create a service is by using the provide() method. This is the only way to create a service that we can configure using the .config() function. Unlike the previous to methods, we’ll set the injectables in a defined this.$get() function definition.
Syntactic Sugar is the difference. Only provider is needed. Or in other words only provider is the real angular, all other ones are derived(to reduce code). There is a simple version as well, called Value() which returns just the value, no calculation or function. Even Value is derived from provider! So why such complications, why can't we just use provider and forget everything else? It is supposed to help us write code easily and communicate better. And toungue-in-cheek reply would be, the more complex it gets the better selling a framework will be. A provider that can return value = Value A provider that can just instantiate and return = Factory (+ Value) A provider that can instantiate + do something = Service (+ Factory, + Value) A provider = must contain a property called $get (+Factory, + Service, + Value) Angular injection gives us the first hint in reaching this conclusion. "$injector is used to retrieve object instances as defined by provider" not service, not factory but provider. And a better answer would be this: "An Angular service is created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function." So master provider and injector and all will fall in place :) . And it gets interesting in Typescript when $get can be implemented in a provider by inheriting from IServiceProvider.
How to declare an object in Angular JS that isn't a service but doesn't pollute the global scope?
I've since discovered I can return instances of an object by having a get() method in my factory, that returns new service instances. But what if my object isn't a service (talking semantics here). E.G I have a page with many charts on it, the chart object (below) isn't (semantically) a service. So do I have to declare it using something like factory/provider/etc pattern? It feels wrong, as it's not actually a service. But I need to reference it from my controller, so it needs to be injected, or accessible somehow. & I don't want it to pollute the global scope. var Chart = function () { var self = this; this.initialize = function (name, clientMethod, usingDateRange, usesAnalytics, initCB, serviceCB, highchartsConfig) { this.name = name; this.clientMethod = clientMethod; this.usingDateRange = usingDateRange; this.usesAnalytics = usesAnalytics; this.initCB = initCB; this.serviceCB = serviceCB; this.highchartsConfig = highchartsConfig; this.$chart = $('#' + name); this.isIncluded = false; this.highchartsConfig.chart.renderTo = this.name; this.initCB && this.initCB(this); }; };
Look at module.value(). From doc: Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. UPDATE Not sure if you are still interested in it, but I finally found a correct answer to your question - make use of the $controller service. HERE I created a simple demo: app.controller('MainCtrl', function($scope, $controller) { function Person($interpolate, name, surname){ var greetStr = "Hello {{name + ' ' + surname}}!"; var greetExp = $interpolate(greetStr); this.greet = greetExp({name:name, surname:surname}); } $scope.person1 = $controller(Person, {name:"Jack", surname:"Daniels"}); $scope.person2 = $controller(Person, {name:"Johny", surname:"Walker"}); }); (I used $interpolate just to show that angular's DI will automatically resolve any dependencies it is aware of. The rest of dependencies [locals] may be passed as the second argument to the $controller.)
Firebase's AngularFire in an AngularJS service
The best way of handling Firebase in AngularJS surely has to be from within a service, so it's available to all Controllers across the App. I just can't get it to work! ... I first tried using angularFire(new Firebase(url)), hoping I could bind to the service's scope, but Angular complains that it cannot $watch it. So I tried angularFireCollection instead like this: app.factory('myService', function myService(angularFireCollection) { var url = 'https://myfirebase.firebaseio.com'; return { getAll: function(path) { var ref = angularFireCollection(new Firebase(url + '/' + path)); console.log(ref); return ref; }, ... }; }); However, the angularFireCollection is an Object containing a load of methods etc. if I bind it to a controller $scope I just get garbage. It also complains that it can't call the Firebase functions before I try to use them (e.g. Error: Firebase.push failed: second argument must be a valid function.)... anyone got any ideas where I'm going wrong? See this PLUNKER
If you want to encapsulate some of the functionality into a service, consider keeping the returned ref in state of the service. I expanded on your plunker. It seems to mostly do what you were trying for. http://plnkr.co/edit/Uf2fB0
Jeff answered the question correctly ... I'm just posting a further development on Jeff's example for those who are interested. I have abstracted the Firebase service creation, so you can dynamically create an instance of whatever Firebase service you want:- var registerFirebaseService = function (serviceName) { app.factory(serviceName, function (angularFire) { var _url = null; var _ref = null; return { init: function (url) { _url = url; _ref = new Firebase(_url); }, setToScope: function (scope, localScopeVarName) { angularFire(_ref, scope, localScopeVarName); } }; }); }; You first create an instance of the service as follows registerFirebaseService('itemsService'); // create itemsService instance Then you can inject the itemsService service into your controllers. The instance is initialised using your Firebase URL e.g. itemsService.init('https://firebase.firebaseio.com/' + userId + '/items'); The Firebase can now be bound to your controller e.g. itemsService.setToScope($scope, 'items'); adapted PLUNKER
angular.service vs angular.factory
I have seen both angular.factory() and angular.service() used to declare services; however, I cannot find angular.service anywhere in official documentation. What is the difference between the two methods? Which should be used for what (assuming they do different things)?
angular.service('myService', myServiceFunction); angular.factory('myFactory', myFactoryFunction); I had trouble wrapping my head around this concept until I put it to myself this way: Service: the function that you write will be new-ed: myInjectedService <---- new myServiceFunction() Factory: the function (constructor) that you write will be invoked: myInjectedFactory <--- myFactoryFunction() What you do with that is up to you, but there are some useful patterns... Such as writing a service function to expose a public API: function myServiceFunction() { this.awesomeApi = function(optional) { // calculate some stuff return awesomeListOfValues; } } --------------------------------------------------------------------------------- // Injected in your controller $scope.awesome = myInjectedService.awesomeApi(); Or using a factory function to expose a public API: function myFactoryFunction() { var aPrivateVariable = "yay"; function hello() { return "hello mars " + aPrivateVariable; } // expose a public API return { hello: hello }; } --------------------------------------------------------------------------------- // Injected in your controller $scope.hello = myInjectedFactory.hello(); Or using a factory function to return a constructor: function myFactoryFunction() { return function() { var a = 2; this.a2 = function() { return a*2; }; }; } --------------------------------------------------------------------------------- // Injected in your controller var myShinyNewObject = new myInjectedFactory(); $scope.four = myShinyNewObject.a2(); Which one to use?... You can accomplish the same thing with both. However, in some cases the factory gives you a little bit more flexibility to create an injectable with a simpler syntax. That's because while myInjectedService must always be an object, myInjectedFactory can be an object, a function reference, or any value at all. For example, if you wrote a service to create a constructor (as in the last example above), it would have to be instantiated like so: var myShinyNewObject = new myInjectedService.myFunction() which is arguably less desirable than this: var myShinyNewObject = new myInjectedFactory(); (But you should be wary about using this type of pattern in the first place because new-ing objects in your controllers creates hard-to-track dependencies that are difficult to mock for testing. Better to have a service manage a collection of objects for you than use new() wily-nilly.) One more thing, they are all Singletons... Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function. (With the exception of when a factory simply returns a value like a number or string. In that case, you will always get the same value, but not a reference.)
Simply put .. const user = { firstName: 'john' }; // Factory const addLastNameFactory = (user, lastName) => ({ ...user, lastName, }); console.log(addLastNameFactory(user, 'doe')); // Service const addLastNameService = (user, lastName) => { user.lastName = lastName; // BAD! Mutation return user; }; console.log(addLastNameService(user, 'doe'));
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 with 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. Here is example using services and factory. Read more about AngularJS Service vs Factory. You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.
TL;DR 1) When you’re using a Factory you create an object, add properties to it, then return that same object. When you pass this factory into your controller, those properties on the object will now be available in that controller through your factory. app.controller('myFactoryCtrl', function($scope, myFactory){ $scope.artist = myFactory.getArtist(); }); app.factory('myFactory', function(){ var _artist = 'Shakira'; var service = {}; service.getArtist = function(){ return _artist; } return service; }); 2) When you’re using Service, Angular instantiates it behind the scenes with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will return ‘this’. When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. app.controller('myServiceCtrl', function($scope, myService){ $scope.artist = myService.getArtist(); }); app.service('myService', function(){ var _artist = 'Nelly'; this.getArtist = function(){ return _artist; } }); Non TL;DR 1) Factory Factories are the most popular way to create and configure a service. There’s really not much more than what the TL;DR said. You just create an object, add properties to it, then return that same object. Then when you pass the factory into your controller, those properties on the object will now be available in that controller through your factory. A more extensive example is below. app.factory('myFactory', function(){ var service = {}; return service; }); Now whatever properties we attach to ‘service’ will be available to us when we pass ‘myFactory’ into our controller. Now let’s add some ‘private’ variables to our callback function. These won’t be directly accessible from the controller, but we will eventually set up some getter/setter methods on ‘service’ to be able to alter these ‘private’ variables when needed. app.factory('myFactory', function($http, $q){ var service = {}; var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK'; return _finalUrl } return service; }); Here you’ll notice we’re not attaching those variables/function to ‘service’. We’re simply creating them in order to either use or modify them later. baseUrl is the base URL that the iTunes API requires _artist is the artist we wish to lookup _finalUrl is the final and fully built URL to which we’ll make the call to iTunes makeUrl is a function that will create and return our iTunes friendly URL. Now that our helper/private variables and function are in place, let’s add some properties to the ‘service’ object. Whatever we put on ‘service’ we’ll be able to directly use in whichever controller we pass ‘myFactory’ into. We are going to create setArtist and getArtist methods that simply return or set the artist. We are also going to create a method that will call the iTunes API with our created URL. This method is going to return a promise that will fulfill once the data has come back from the iTunes API. If you haven’t had much experience using promises in Angular, I highly recommend doing a deep dive on them. Below setArtist accepts an artist and allows you to set the artist. getArtist returns the artist callItunes first calls makeUrl() in order to build the URL we’ll use with our $http request. Then it sets up a promise object, makes an $http request with our final url, then because $http returns a promise, we are able to call .success or .error after our request. We then resolve our promise with the iTunes data, or we reject it with a message saying ‘There was an error’. app.factory('myFactory', function($http, $q){ var service = {}; var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK' return _finalUrl; } service.setArtist = function(artist){ _artist = artist; } service.getArtist = function(){ return _artist; } service.callItunes = function(){ makeUrl(); var deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }).success(function(data){ deferred.resolve(data); }).error(function(){ deferred.reject('There was an error') }) return deferred.promise; } return service; }); Now our factory is complete. We are now able to inject ‘myFactory’ into any controller and we’ll then be able to call our methods that we attached to our service object (setArtist, getArtist, and callItunes). app.controller('myFactoryCtrl', function($scope, myFactory){ $scope.data = {}; $scope.updateArtist = function(){ myFactory.setArtist($scope.data.artist); }; $scope.submitArtist = function(){ myFactory.callItunes() .then(function(data){ $scope.data.artistData = data; }, function(data){ alert(data); }) } }); In the controller above we’re injecting in the ‘myFactory’ service. We then set properties on our $scope object that are coming from data from ‘myFactory’. The only tricky code above is if you’ve never dealt with promises before. Because callItunes is returning a promise, we are able to use the .then() method and only set $scope.data.artistData once our promise is fulfilled with the iTunes data. You’ll notice our controller is very ‘thin’. All of our logic and persistent data is located in our service, not in our controller. 2) Service Perhaps the biggest thing to know when dealing with creating a Service is that that it’s instantiated with the ‘new’ keyword. For you JavaScript gurus this should give you a big hint into the nature of the code. For those of you with a limited background in JavaScript or for those who aren’t too familiar with what the ‘new’ keyword actually does, let’s review some JavaScript fundamentals that will eventually help us in understanding the nature of a Service. To really see the changes that occur when you invoke a function with the ‘new’ keyword, let’s create a function and invoke it with the ‘new’ keyword, then let’s show what the interpreter does when it sees the ‘new’ keyword. The end results will both be the same. First let’s create our Constructor. var Person = function(name, age){ this.name = name; this.age = age; } This is a typical JavaScript constructor function. Now whenever we invoke the Person function using the ‘new’ keyword, ‘this’ will be bound to the newly created object. Now let’s add a method onto our Person’s prototype so it will be available on every instance of our Person ‘class’. Person.prototype.sayName = function(){ alert('My name is ' + this.name); } Now, because we put the sayName function on the prototype, every instance of Person will be able to call the sayName function in order alert that instance’s name. Now that we have our Person constructor function and our sayName function on its prototype, let’s actually create an instance of Person then call the sayName function. var tyler = new Person('Tyler', 23); tyler.sayName(); //alerts 'My name is Tyler' So all together the code for creating a Person constructor, adding a function to it’s prototype, creating a Person instance, and then calling the function on its prototype looks like this. var Person = function(name, age){ this.name = name; this.age = age; } Person.prototype.sayName = function(){ alert('My name is ' + this.name); } var tyler = new Person('Tyler', 23); tyler.sayName(); //alerts 'My name is Tyler' Now let’s look at what actually is happening when you use the ‘new’ keyword in JavaScript. First thing you should notice is that after using ‘new’ in our example, we’re able to call a method (sayName) on ‘tyler’ just as if it were an object - that’s because it is. So first, we know that our Person constructor is returning an object, whether we can see that in the code or not. Second, we know that because our sayName function is located on the prototype and not directly on the Person instance, the object that the Person function is returning must be delegating to its prototype on failed lookups. In more simple terms, when we call tyler.sayName() the interpreter says “OK, I’m going to look on the ‘tyler’ object we just created, locate the sayName function, then call it. Wait a minute, I don’t see it here - all I see is name and age, let me check the prototype. Yup, looks like it’s on the prototype, let me call it.”. Below is code for how you can think about what the ‘new’ keyword is actually doing in JavaScript. It’s basically a code example of the above paragraph. I’ve put the ‘interpreter view’ or the way the interpreter sees the code inside of notes. var Person = function(name, age){ //The line below this creates an obj object that will delegate to the person's prototype on failed lookups. //var obj = Object.create(Person.prototype); //The line directly below this sets 'this' to the newly created object //this = obj; this.name = name; this.age = age; //return this; } Now having this knowledge of what the ‘new’ keyword really does in JavaScript, creating a Service in Angular should be easier to understand. The biggest thing to understand when creating a Service is knowing that Services are instantiated with the ‘new’ keyword. Combining that knowledge with our examples above, you should now recognize that you’ll be attaching your properties and methods directly to ‘this’ which will then be returned from the Service itself. Let’s take a look at this in action. Unlike what we originally did with the Factory example, we don’t need to create an object then return that object because, like mentioned many times before, we used the ‘new’ keyword so the interpreter will create that object, have it delegate to it’s prototype, then return it for us without us having to do the work. First things first, let’s create our ‘private’ and helper function. This should look very familiar since we did the exact same thing with our factory. I won’t explain what each line does here because I did that in the factory example, if you’re confused, re-read the factory example. app.service('myService', function($http, $q){ var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK' return _finalUrl; } }); Now, we’ll attach all of our methods that will be available in our controller to ‘this’. app.service('myService', function($http, $q){ var baseUrl = 'https://itunes.apple.com/search?term='; var _artist = ''; var _finalUrl = ''; var makeUrl = function(){ _artist = _artist.split(' ').join('+'); _finalUrl = baseUrl + _artist + '&callback=JSON_CALLBACK' return _finalUrl; } this.setArtist = function(artist){ _artist = artist; } this.getArtist = function(){ return _artist; } this.callItunes = function(){ makeUrl(); var deferred = $q.defer(); $http({ method: 'JSONP', url: _finalUrl }).success(function(data){ deferred.resolve(data); }).error(function(){ deferred.reject('There was an error') }) return deferred.promise; } }); Now just like in our factory, setArtist, getArtist, and callItunes will be available in whichever controller we pass myService into. Here’s the myService controller (which is almost exactly the same as our factory controller). app.controller('myServiceCtrl', function($scope, myService){ $scope.data = {}; $scope.updateArtist = function(){ myService.setArtist($scope.data.artist); }; $scope.submitArtist = function(){ myService.callItunes() .then(function(data){ $scope.data.artistData = data; }, function(data){ alert(data); }) } }); Like I mentioned before, once you really understand what ‘new’ does, Services are almost identical to factories in Angular.
The clue is in the name Services and factories are similar to one another. Both will yield a singleton object that can be injected into other objects, and so are often used interchangeably. They are intended to be used semantically to implement different design patterns. Services are for implementing a service pattern A service pattern is one in which your application is broken into logically consistent units of functionality. An example might be an API accessor, or a set of business logic. This is especially important in Angular because Angular models are typically just JSON objects pulled from a server, and so we need somewhere to put our business logic. Here is a Github service for example. It knows how to talk to Github. It knows about urls and methods. We can inject it into a controller, and it will generate and return a promise. (function() { var base = "https://api.github.com"; angular.module('github', []) .service('githubService', function( $http ) { this.getEvents: function() { var url = [ base, '/events', '?callback=JSON_CALLBACK' ].join(''); return $http.jsonp(url); } }); )(); Factories implement a factory pattern Factories, on the other hand are intended to implement a factory pattern. A factory pattern in one in which we use a factory function to generate an object. Typically we might use this for building models. Here is a factory which returns an Author constructor: angular.module('user', []) .factory('User', function($resource) { var url = 'http://simple-api.herokuapp.com/api/v1/authors/:id' return $resource(url); }) We would make use of this like so: angular.module('app', ['user']) .controller('authorController', function($scope, User) { $scope.user = new User(); }) Note that factories also return singletons. Factories can return a constructor Because a factory simply returns an object, it can return any type of object you like, including a constructor function, as we see above. Factories return an object; services are newable Another technical difference is in the way services and factories are composed. A service function will be newed to generate the object. A factory function will be called and will return the object. Services are newable constructors. Factories are simply called and return an object. This means that in a service, we append to "this" which, in the context of a constructor, will point to the object under construction. To illustrate this, here is the same simple object created using a service and a factory: angular.module('app', []) .service('helloService', function() { this.sayHello = function() { return "Hello!"; } }) .factory('helloFactory', function() { return { sayHello: function() { return "Hello!"; } } });
All the answers here seem to be around service and factory, and that's valid since that was what was being asked about. But it's also important to keep in mind that there are several others including provider(), value(), and constant(). The key to remember is that each one is a special case of the other. Each special case down the chain allowing you to do the same thing with less code. Each one also having some additional limitation. To decide when to use which you just see which one allows you to do what you want in less code. Here is an image illustrating just how similar they are: For a complete step by step breakdown and quick reference of when to use each you can visit the blog post where I got this image from: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
app.factory('fn', fn) vs. app.service('fn',fn) Construction With factories, Angular will invoke the function to get the result. It is the result that is cached and injected. //factory var obj = fn(); return obj; With services, Angular will invoke the constructor function by calling new. The constructed function is cached and injected. //service var obj = new fn(); return obj; Implementation Factories typically return an object literal because the return value is what's injected into controllers, run blocks, directives, etc app.factory('fn', function(){ var foo = 0; var bar = 0; function setFoo(val) { foo = val; } function setBar (val){ bar = val; } return { setFoo: setFoo, serBar: setBar } }); Service functions typically do not return anything. Instead, they perform initialization and expose functions. Functions can also reference 'this' since it was constructed using 'new'. app.service('fn', function () { var foo = 0; var bar = 0; this.setFoo = function (val) { foo = val; } this.setBar = function (val){ bar = val; } }); Conclusion When it comes to using factories or services they are both very similar. They are injected into a controllers, directives, run block, etc, and used in client code in pretty much the same way. They are also both singletons - meaning the same instance is shared between all places where the service/factory is injected. So which should you prefer? Either one - they are so similar that the differences are trivial. If you do choose one over the other, just be aware how they are constructed, so that you can implement them properly.
I have spent some time trying to figure out the difference. And i think the factory function uses the module pattern and service function uses the standard java script constructor pattern.
The factory pattern is more flexible as it can return functions and values as well as objects. There isn't a lot of point in the service pattern IMHO, as everything it does you can just as easily do with a factory. The exceptions might be: If you care about the declared type of your instantiated service for some reason - if you use the service pattern, your constructor will be the type of the new service. If you already have a constructor function that you're using elsewhere that you also want to use as a service (although probably not much use if you want to inject anything into it!). Arguably, the service pattern is a slightly nicer way to create a new object from a syntax point of view, but it's also more costly to instantiate. Others have indicated that angular uses "new" to create the service, but this isn't quite true - it isn't able to do that because every service constructor has a different number of parameters. What angular actually does is use the factory pattern internally to wrap your constructor function. Then it does some clever jiggery pokery to simulate javascript's "new" operator, invoking your constructor with a variable number of injectable arguments - but you can leave out this step if you just use the factory pattern directly, thus very slightly increasing the efficiency of your code.