As discussed in the comments, although there is already an accepted answer, it shows only one way to update a given in Factory. Another method, and perhaps one of the best Angularjs tools, is to update the data by reference, that is, instead of calling a function that updates the data, you create a scope with reference to an object in Factory.
So when there is an update, be it in controller, Directive, Component, etc. The value in Factory will also be updated.
But, for this to work, you must follow a basic rule: Every value to be referenced must be defined within Factory. See this example:
angular.module(appModule)
.factory('empresaFactory', function() {
//Factory
const empresa = {}; //Esse objeto é apenas uma referência geral da factory, para que você acesse os dados ou funções;
// Aqui declaramos os dados
empresa.dados = {}; //Dados da empresa
empresa.produtos = []; //Lista de produtos da empresa
// Aqui declaramos as funções
/**
* Função para atualizar os dados (declarados acima) após obter o endpoint de sua api
*/
empresa.atualizaEmpresa= function(campo, valor) {
return angular.extend(empresa[campo], valor); //Não sei se é extremamente necessário utilizar o extend, mas quando eu não utilizo desse modo, o comportamento é irregular
}
// Retornamos a factory
return empresa;
})
As you can see, I created 2 references (object) empresa.dados
and (array) empresa.produtos
where we will store the data. As soon as you get the data, for example, loaded the company data from the database, you call the function empresa.atualizaDados
to create the initial object, thus:
controller
$scope.empresa = empresaFactory.dados; //Cria a referência
empresaFactory.atualizaEmpresa('dados', $scope.dadosDaEmpresa); //Semelhante a primeira respota
//Ou deste modo
$scope.empresa = dadosDaApi; //dados obtidos do seu banco de dados
//Ou atualizar apenas um valor
$scope.empresa.nome = 'Novo nome da empresa';
$scope.empresa.cnpj = '11.222.333/0000-99';
The same thing goes for the array, you can do all the manipulation, see:
controller
$scope.produtos = empresaFactory.produtos;
$scope.produtos.push(novoProduto); //Adiciona um produto
$scope.produtos.splice(index, 1); //Remove um produto
All these updates I mentioned, they will reflect the result directly in the "source", ie in Factory, without calling the update manually.
Important!!!
Note that I still call a manual update at the Factory with this: empresaFactory.atualizaEmpresa('dados', $scope.dadosDaEmpresa);
. I, particularly, I do this because when I get the initial data, it’s done within the solve of my state, so it’s just a more practical way, because I don’t need to create a reference just to update. I just update direct as parameter.
But that’s up to you.
I hope that I have been able to explain this clearly and that you will learn more about it. This method will help you if you have a complex application with data sharing in many locations.
How is your controller?
– celsomtrindade
I updated with the controller, @Celsomtrindade. It was just a parameter, I don’t know how I didn’t think of it.
– Fernando Zabin
Yes. One of the modes is to pass as parameter. You can also make a reference. Thus, you update in the controller and it automatically updates in Factory, without having to pass parameter. If you are interested, I can elaborate another answer addressing this method =D
– celsomtrindade
Oops, yes I do. It’s always good to learn other ways to implement, and it will complement the answer too.
– Fernando Zabin
Answered Fernando! = D
– celsomtrindade