Reapply function in 2 different controllers

5

I have the same function in 2 different controllers.

This is not a good practice because it will complicate code maintenance.

How do I reuse the same code on different controllers? Using "factory", "service" ...?

I have deleted the directive because I do not have DOM manipulation and the function also does not depend on the DOM, I just step one parameter and via $ http, I check if the record exists in the database, returning true / false.     

asked by anonymous 06.03.2015 / 12:23

1 answer

1

Using a service or factory are the best choices because you can incorporate them to controller easily.

The skeleton of a service is simple:

//Criando o service
angular.module('services', [])
.service('meuService', function() {
  var valor1 = '1';
  this.metodo1 = function () {
    alert('Função' + valor1);
  }
});

//Fazendo uso do service
angular.module('controllers', [])
.controller('meuController', function ($scope, meuService) {
  $("button").click = function () {
    meuService.metodo1();
  };
});

The skeleton of a factory is already different:

//Criando o service por factory
angular.module('services2', [])
.factory('meuService2', function () {
  var service.valor = '1';

  service.funcao = function () {
    alert('Função');
  };

  return service;
});

//Fazendo uso do service
angular.module('controllers2', [])
.controller('meuController2', function ($scope, meuService2) {
  $scope.fun1 = function () {
    meuService2.funcao();
  };
}
    
06.03.2015 / 12:59