2 Controllers with the same API

0

My knowledge in angular is little yet and I have doubts even a little dizzy, but come on hehe. I need a controller that shows recent records (8 latest) and another with a general list (20 items). See my reasoning below.

var app = angular.module('myApp', []);
  app.controller('recentesCtrl', function($scope, $http) {
     $scope.loading = true;
     $scope.limitM = 8;
     $http.get("http://www.folhacar.com.br/api/listAnuncios?revenda_id=528&cnpj=13733235000134")
     .success(function (data) {$scope.nomes = data;}).finally(function() {
     $scope.loading = false;
      });

app.controller('listaCompletaCtrl', function($scope, $http) {
     $scope.loading = true;
     $scope.limitM = 20;
     $http.get("http://www.folhacar.com.br/api/listAnuncios?revenda_id=528&cnpj=13733235000134")
     .success(function (data2) {$scope.nomes2 = data2;}).finally(function() {
     $scope.loading = false;
     });
});

I'm not sure how I can do this effectively, since the 2 controllers are using the same API, same url, and everything.

    
asked by anonymous 14.07.2015 / 16:35

1 answer

0

You can create a service to organize / reuse your code, for example:

var MyService = angular.module('MyService', [])
.service('TestServ', function () {
    this.methodAPI = function (limit) { 
          $scope.limitM = limit;
          $scope.loading = true;
          $http.get("http://www.folhacar.com.br/api/listAnuncios?revenda_id=528&cnpj=13733235000134")
     .success(function (data) {$scope.nomes = data;}).finally(function() {
     $scope.loading = false;
};

});

var app = angular.module('myApp', ['MyService']);
  app.controller('recentesCtrl', function($scope, $http, TestServ) {
      $scope.callService = function () {
        TesteServ.methodAPI(8);
    }   

});

  app.controller('listaCompletaCtrl', function($scope, $http, TestServ) {
      $scope.callService = function () {
        TesteServ.methodAPI(20);
    }     
});
    
14.07.2015 / 17:56