1.

What is the difference between factory and service in AngularJS?

Answer»
ServiceFactory
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.
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;
  }
});



Discussion

No Comment Found