What is the difference between Factory, service or controller in Angular?

Asked

Viewed 7,086 times

11

Next, in practice, what’s the difference and how to do service with . service, . Factory and controller?

service js.

angular.module('app.services', [])

.factory('BlankFactory', [function(){

}])

.service('BlankService', [function(){

}]);

controller js.

angular.module('app.controllers', [])

.controller('servicoControler', function($scope) {

})

I saw this video, but I didn’t understand the difference: Angular Factory vs Service

  • See if the answer to this question helps you: http://stackoverflow.com/questions/13762228/confused-about-service-vs-factory

  • Factory resume function and service values returns nothing, only the argument passed in the Function parameter, correct?

1 answer

19


The controller would be the mediator leading of his model and its view. In it you would make the necessary manipulations for interaction with the services of your application. When I say services, I do not refer strictly to the service, but also to .factory, at the .provider, at the .config and to the .value.

Factory

The name Factory refers to Factory Function, which are those functions that return an object. For example:

var pessoa = function(nome, idade) {
  return {
    nome: nome,
    idade: idade
  }
}
var maria = pessoa("Maria", 23);
maria.idade; // 23

It is in this structure that the Factory works. On it you return a reusable object (main issue of services - reusability) in the controller, from the parameter passed. For example:

.factory('usersAPI', [function($http){
     var _getUsers = function(){
         return $http.get('/users');
     };
     return{
        getUsers: _getUsers
     }
}])

Service

Already the service works in the structure of a Constructor Function:

var Pessoa = function(nome, idade) {
  this.nome = nome;
  this.idade = idade;
}
var maria = new Pessoa("Maria", 23);
maria.idade; // 23

These also function as an object, but do not return it. They work with the use of this. Example that does the same thing from the example with the Factory:

.service('usersAPI', function($http) {
  this.getUsers = function() {
    return $http.get('/users');
  };
})

In the controller to call one of these services would simply add your script and add the dependency with your name:

.controller('servicoControler', function($scope, usersAPI) {
    usersAPI.getUsers(); // retorna o get
})

In the example above, this same code would work for the two cases already said. Like the two, in the example, have the same name, it would be advisable to use only one service.

It is all a matter of structuring, design and mainly reusability of code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.