2 Controllers with the same API

Asked

Viewed 99 times

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 last) and another with a general list (of 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;
     });
});

It’s definitely not right, how can I do it efficiently when the 2 controllers are using the same API, same url and all.

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);
    }     
});
  • For some reason it doesn’t work :(

  • What error occurs? This content talks about service >> Link

Browser other questions tagged

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