Reuse function in 2 different controllers

Asked

Viewed 1,487 times

5

I have the same function in 2 different controllers.

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

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

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

1 answer

1

The use of a service or factory are the best choices as you can incorporate them into the 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();
  };
}
  • So the difference between Factory and service is that the former uses the concept of closure and the latter does not.

Browser other questions tagged

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