Autocomplete with call Ajax in AngularJS

2

I want to implement an AutoComplete using an Ajax call for example:

this.getCliente = function(data){
    return $http.post(UrlobtenerDatosUsuario,data);
 }

which returns a Json according to the parameters that it sends. Now once the data is obtained, perform the search using autocomplete from 3 digits.

Can someone please help me by giving me some guidance?

    
asked by jose.luis.lopez 03.08.2016 в 03:22
source

1 answer

1

To do this you can assign a model for the search input and listen to the changes with ng-change using a delay with $timeout to give time to the user who finishes entering your search, then you take that value to make the request to the server and finally samples N number of results in a list. Here I give you an example:

Template:

<input type="text" ng-model="textoBusqueda" ng-change="buscar(textoBusqueda)"> 

<span ng-show="cargando">Cargando...</span>

<div class="resultadosBusqueda">
    <ul>
      <li ng-repeat="sugerencia in results" ng-click="clienteSeleccionado = sugerencia">
        {{ sugerancia.nombre }}
      </li>
    </ul>
  </div>

  <h2 ng-if="clienteSelecionado">
    <Strong>Cliente Seleccionado: </Strong> {{ clienteSeleccionado.nombre }}
  </h2>

Controller:

angular.module('app.clientes')
.controller('clientesCtrl', ['$scope', '$timeout', '$http', 
    function($scope, clientesService, $timeout, $http){
      $scope.results = [];
      $scope.cargando = false;
      $scope.clienteSeleccionado = null;

      var URL_CLIENTES = 'api/v1/clientes/';

      // Autocompletado Busqueda 
      var timer = null;
      $scope.buscar = function(val){
        if(timer) $timeout.cancel(timer);
        timer = $timeout(exc, 800); //800 milisegundos de retardo
        function exc(){
          console.log('buscando...');
          $scope.getClientes(val);
        }
      }

      // Llamada al servidor
      $scope.getClientes = function(val){
        $scope.cargando = true; //mostrar "cargando en la vista"
        return $http.post(URL_CLIENTES+'?limit=10', { q: val}).then(function(response){
            console.log(response);
            $scope.results = response.data; 
            $scope.cargando = false;
        }); 
      };
}]);

Using css you can give styles to the ul>li so that it comes out in form attached to the inputs as options to complete.

    
answered by 31.10.2016 в 04:05