Call function of another non-angular controller

2

I have this controller :

myApp.controller('listarClientesController', function($scope, $http){

$scope.lista = listarClientes();

function listarClientes() {
    $http({
      method: 'GET',
      url: baseUrl + '/index.php/Clientes/Listar'
    }).then(function successCallback(response) {
        $scope.clientes = response.data;
      }, function errorCallback(response) {
        toastr["error"]("Erro ao obter os registros", "Sistema");
    });
}}); 

I need to call listarClientes after successfully inserting this controller :

myApp.controller('cadastrarClienteController', function($scope, $http)

  $scope.cadastrarCliente = function () {

  $scope.cliente = {
    CliNome: $scope.cliente.CliNome,
    CliTelefone: $scope.cliente.CliTelefone,
    CliEmail: $scope.cliente.CliEmail,
    CliDescricao: $scope.cliente.CliDescricao
   };

var response = $http({
    method: "POST",
    url: baseUrl + "/index.php/Clientes/create",
    data: $scope.cliente,
    dataType: "json"
}).then(function successCallback(response) {
    toastr["success"]("Registro inserido com sucesso!", "Sistema");
  }, function errorCallback(response) {
    toastr["error"]("Erro ao inserir o registro", "Sistema");
});

$scope.lista;

return response;

Edit:

Service:

myApp.service('clienteService', function($scope, $http){

this.listarClientes = function() {
    $http({
      method: 'GET',
      url: baseUrl + '/index.php/Clientes/Listar'
    }).then(function successCallback(response) {
        $scope.clientes = response.data;
      }, function errorCallback(response) {
        toastr["error"]("Erro ao obter os registros", "Sistema");
    });
}});

Edit:

so I declare in the controller:

myApp.controller('cadastrarClienteController', function($scope, $http, clienteService){

Repair:

myApp.service('clienteService', function($http){
this.ListarClientes = function() {
    return $http.get(baseUrl + '/index.php/Clientes/Listar');
}

});

Thank you!

    
asked by anonymous 15.07.2016 / 19:54

1 answer

3

If you are consuming the same data source from multiple places in your application it may be worth implementing your source as a service or factory , as indicated in the Gabriel :

.factory(
    "clientesFactory", function ($resource) {
        return $resource("/index.php/Clientes/Listar");
    })

And consume this factory where you need it:

myApp.controller('listarClientesController', function($scope, clientesFactory){
    clientesFactory.query(function(data){ $scope.lista = data; });
}
    
15.07.2016 / 20:10