-->

Implement autocomplete textbox in AngularJS



Introduction

This article explains how to implement an autocomplete textbox in AngularJS.

The Autocomplete textbox widget is used for provides suggestions while user type into the input field (textbox). You noticed how the related suggestions highlight when we start typing in the Google search box, this is called autocomplete.

We know that AngularJS is a very popular framework nowadays for build highly interactive web applications and for making our application more interactive, we can create this autocomplete textbox in our AngularJS application.

Here in this application, we have used angucomplete-alt AngularJS directive for creating autocomplete textbox.

In the previous article, I have explained how to implement autocomplete textbox in ASP.NET without using Webservice. Today I will show you, how to implement an autocomplete textbox in AngularJS.

Just follow the following steps in order to implement "autocomplete textbox in AngularJS".

Here In this article, I have used Visual Studio 2013

Step - 1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Entry Application Name > Click OK > Select Empty template > Checked MVC (under "Add folders and core references for" option) > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table for store data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have created a table (see below image) for store country names for showing in autosuggestion ion list.  


Countries Table 

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add angucomplete-alt.js (angular directive) script file into our application.

Here in this article, we have used angucomplete-alt.js AngularJS directive forcreatinge autocomplete textbox.
If "Scripts" folder not added in your application, add Script folder first
Right Click on project from solution explorer > Add > new folder > Rename "Scripts" and then
Right click on that folder > Add > Existing Item... > select the angucomplete-alt.js file > Add.

Step-6: Add angucomplete-alt.css file into our application.

Here I have added a folder "Content" in our application
Right Click on project from solution explorer > Add > new folder > Rename "Content" and then
Right click on that folder > Add > Existing Item... > select the angucomplete-alt.css file > Add.

Step-7: Create a javascript file for angular components.

Here I have added a javascript file in the "Scripts" folder for add angular components (module, controller etc).

Right click on your "Scripts" folder > Add > New Item > select "javascript" file > Enter name (here "myApp.js")> Ok.
Write following code
var app = angular.module('myApp', ['angucomplete-alt']);
app.controller('ngAutoCompleteController', ['$scope', '$http', function ($scope, $http) {
    $scope.Countries = [];
    $scope.SelectedCountry = null;


    //After select country event
    $scope.afterSelectedCountry = function (selected) {
        if (selected) {
            $scope.SelectedCountry = selected.originalObject;
        }
    }

    //Populate data from database 
    $http({
        method: 'GET',
        url:'/home/GetCountries'
    }).then(function (data) {
        $scope.Countries = data.data;
    }, function () {
        alert('Error');
    })
}]);
you can see here I have included the angucomplete-alt module in our module (here "myApp") for implement autocomplete textbox in our AangularJS application. 

Step-8: Create an MVC Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"

Step-9: Add new action into your controller. 

Here I have added "Index" Action into "Home" Controller. Please write this following code
public ActionResult Index()
{
   return View();
}

Step-10: Add view for your Action and design.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
HTML Code
@{
    ViewBag.Title = "Index";
}
@* HTML *@
<div class="container">
    <h2>Autocomplete textbox in AngularJS</h2>
    <div ng-app="myApp">
        <div ng-controller="ngAutoCompleteController">
            <div angucomplete-alt id="txtAutocomplete" placeholder="Type country name" pause="100"
                 selected-object="afterSelectedCountry" local-data="Countries" search-fields="CountryName"
                 title-field="CountryName" minlength="1" input-class="form-control" match-class="highlight">

            </div>
            <div ng-show="SelectedCountry">
                Selected Country : {{SelectedCountry.CountryName}}
            </div>
        </div>
    </div>
</div>

@* JS *@
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.min.js"></script>
<script src="~/Scripts/angucomplete-alt.js"></script>
<script src="~/Scripts/myApp.js"></script>
@* CSS *@
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/angucomplete-alt.css" rel="stylesheet" />
<style type="text/css">
.angucomplete-dropdown {
    overflow-y: auto;
    max-height: 200px; 
}
</style>

Step-11: Add an another action in our MVC controller for fetch data from the database.

public JsonResult GetCountries()
{
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var v = dc.Countries.OrderBy(a => a.CountryName).ToList();
        return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

Step-12: Run Application.


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.