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();
};
}