homepage >> AngularJS autocomplete form field    
 

Yossef Benharosh is an apt web developer and the author of the eBook The essentials of object oriented PHP.

Yossef Benharosh web developer profile linkedin twitter github

AngularJS autocomplete form field

My way of doing autocomplete with AngularJS.

Demo


  • {{ item.label }}
Start typing any country

Code

HTML form

<div data-ng-app="myApp">
  <form role="form" data-ng-controller="myCtrl">
    <div class="form-item">
      <label for="destination">Destination</label>

      <input  type="hidden"
        class="form-control" 
        id="destination" 
        name="destination" 
        data-ng-model="formData.destination" />
		
      <input  type="text"
        class="form-control" 
        id="destination_visible" 
        name="destination_visible" 
        data-ng-model="formData.destinationVisible" 
        data-ng-keyup="listenWhileTyping()" />
		
      <ul class="hints" data-ng-if="autocompleteList.length > 0">
        <li data-ng-repeat="item in autocompleteList" 
        data-ng-click="selectDestination(+item.value, item.label)">
        {{ item.label }}
        </li>
      </ul>
    </div>
  </form>
</div>

 

JS script

var myApp = angular.module('myApp', []);

myApp.controller('myCtrl', function($scope, $http, $timeout){
  $scope.formData = {
    destination: {'label': 'select', 'value': 0},
    destinationVisible: '',
  }

  $scope.autocompleteList = [];
	
  $scope.selectDestination = function(val, label){
    var obj = {label:label,value:val};

    $scope.formData.destinationVisible = label;
    $scope.formData.destination = obj;

    $scope.autocompleteList = [];
  };
	
  $scope.autoCompleteCountries = function(hint){
    if(hint.trim().length < 1) { 
      $scope.autocompleteList = {value:0};
        return; 
      }
      
      hint = hint.trim();
      $http({
        method: 'POST',
        url: '/autocomplete-countries',
        data: {'hint': hint}
      }).then(function (data) {
        if(data.status == 200 && typeof data.data != 'undefined'){
          $scope.autocompleteList = data.data;
        } else {
          $scope.autocompleteList = [];
        }
      });
  };
	
  $scope.listenWhileTyping = function(){
    $scope.autoCompleteCountries($scope.formData.destinationVisible);
  };
});

 

CSS

form .form-item{
    position:relative;
}
form .hints{
    position:absolute;
    list-style-type:none;
}
form .hints li{
    list-style-type:none;
    border-top-left-radius: .25rem;
    border-top-right-radius: .25rem;
    position: relative;
    display: block;
    padding: .75rem 1.25rem;
    margin-bottom: -1px;
    background-color: #fff;
    border: 1px solid rgba(0,0,0,.125);
    cursor:pointer;
}

 

Server side

In my case, I use PHP with PDO extension to interact with mySQL database.

<?php

# Consult your hosting provider for the headers to use
header("Access-Control-Allow-Origin: MY_WEBSITE.COM"); // *
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET,POST"); // HEAD,OPTIONS
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

header('Content-Type: application/json');

$credentials = array (
    'database' => DB_NAME,
    'username' => DB_USER,
    'password' => DB_PASS,
    'host'     => DB_HOST,
);

try {
  $dbh = new PDO('mysql:host='.$credentials['host'].';dbname='.$credentials['database'], 
                 $credentials['username'], 
                 $credentials['password'],
                array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
} catch (PDOException $e) {
  print "Error!: " . $e->getMessage();
  die();
}

$postdata = file_get_contents("php://input");

if(isset($postdata) && !empty($postdata))
{
	$request = json_decode($postdata);
	
	$hint = preg_replace("/[^a-z ]/", '', $request->hint);

    $sql = "SELECT name as label, id as value 
            FROM countries 
            WHERE name LIKE '%{$hint}%' LIMIT 10";
    
    $query = $dbh -> prepare($sql);
    $query -> execute();
    $res = $query -> fetchAll(PDO::FETCH_OBJ);
    //var_dump($query -> rowCount());
    if($query -> rowCount() > 0)
    {
      $count = $query -> rowCount();
      echo(json_encode($res)); exit;
    }
}
echo(json_encode([])); exit;

 

Database

Here I use mySQL table as my data source. You can download a zip file containing the "countries" SQL table.