How to create a facebook style autocomplete using AngularJS

This tutorial explains how to show autocomplete results for a textbox input using AngularJS, PHP and MySQL with the help of Angular UI directive.

facebook type autocomplete using php mysql angularjs

Live Demo Download

To achieve the desired autocomplete functionality, We will be using Bootstrap UI directive library for AngularJS.

Angular UI Directives: A library of essential bootstrap components written in pure AngularJS by AngularUI Team.

Its easy to set up
Download and include the js file in index.html.

<script src="js/angular.min.js" type="text/javascript"></script>  
<script src="js/ui-bootstrap-tpls-0.9.0.js"></script>  
<script src="app/app.js" type="text/javascript"></script>  

Inject the dependency on the ui.bootstrap module and get the data from the database using $ajax at your app.js file

var app = angular.module(‘myApp’, [‘ui.bootstrap’]);

app.controller(‘autocompleteController’, function($scope, $http) {  
 getCountries(); // Load all countries with capitals  
 function getCountries(){  
 $scope.countries = data;  

Create a custome template to hold the output at your autocomplete.html file

<script id="customTemplate.html" type="text/ng-template"><a><span bind-html-unsafe="match.label | typeaheadHighlight:query"><i>({{match.model.capital}})</script>  

Bind the typeahead directive into your input field.

<input class="form-control" ng-model="selectedCountries" placeholder="Search Countries" style="width:350px;" type="text" typeahead="c as c.country for c in countries | filter:$viewValue | limitTo:10" typeahead-min-length="1" typeahead-on-select="onSelectPart($item, $model, $label)" typeahead-template-url="customTemplate.html"></input>  

Import the countries.sql into your database which contains country names and capitals

The getCountries.php file which gets all the countries with capitals from MySQL database

<?php require_once '../includes/config.php';

$query="select distinct c.country, c.capital from countries c order by 1";
$result = $mysqli-?>
query($query) or die($mysqli->error.__LINE__);

$arr = array();  
 if($result->num_rows > 0) {  
 while($row = $result->fetch_assoc()) {  
 $arr[] = $row;  

# JSON-encode the response  
 echo $json_response = json_encode($arr);  

This will populate the countries scope, Which in turn binds to our Search Countries input