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

11

Next, in practice, what is the difference and how do you 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 watched this video, but I did not understand the difference: Angular Factory vs Service

    
asked by anonymous 22.01.2016 / 20:15

1 answer

17

controller would be the principal mediator of your model and your view . In it you would make the necessary manipulations to interact with the services of your application. When I say services, I am not strictly referring to service , but also to .factory , .provider , .config and .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 factory works. In it you return a reusable object (the main services question - reusability) in the controller , from the passed parameter. For example:

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

Service

Service already works on 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 work as an object, but do not return it. They work with this . Example that does the same thing with the factory example:

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

controller to call one of these services would just 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. Because both in the example have the same name, it would be advisable to use only one service.

It's all about structuring, designing and reusability of the code.

    
23.01.2016 / 02:31