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.
See if the answer to this question helps you: http://stackoverflow.com/questions/13762228/confused-about-service-vs-factory
– adelmo00
Factory resume function and service values returns nothing, only the argument passed in the Function parameter, correct?
– GustavoSevero