What is the difference between factory and service in AngularJS?
Service | Factory |
---|---|
Creates a service object in Angular by using the "new" keyword. | In Angular, factories are the most popular way to create and configure a service. |
It does not use a type-friendly injection mode. | It uses a type-friendly injection mode. |
It cannot create primitives. | Factory can be used to build primitives. |
It is configurable. | It is not configurable. |
BY Best Interview Question ON 19 Jun 2020
Example
Example of a Factory in Angular
app.controller('myFactoryCtrl', function ($scope, myFactory) {
$scope.artist = myFactory.getArtist()
})
app.factory('myFactory', function () {
var _artist = '';
var service = {}
service.getArtist = function () {
return _artist
}
return service;
})
Example of a Service in Angular
app.controller('myServiceCtrl', function ($scope, myService) {
$scope.artist = myService.getArtist();
});
app.service('myService', function () {
var _artist = '';
this.getArtist = function () {
return _artist;
}
});