Implement Auto Complete TextBox Using AngularJS In MVC5

I have noticed in some search engines and websites that while I am typing the first two letters of a word, it shows me a suggested list to select. These auto complete text boxes are mostly used in real time projects to increase  user interactivity with the site. Now in this post, we will look at how this is implemented in AngularJS.

For example, let's talk about the Google auto complete search box.

Here, the suggested results will come based on the previous search results or most searched results.

Implementing Auto Complete Textbox in Angular

To implement an auto complete text box in Angular, we need a angucomplete-alt directive. Angucomplete dependency should be added to the Angular Application. In this application, I am getting the data suggestion from the database table.

Steps to implement Auto complete text box are:

Step 1

Create New Project.

Go to File -> New -> Project -> ASP.NET Web Application under Web section -> Entry Application Name -> OK -> Empty template -> Checked MVC ->OK

Step 2

Add a database to the project.

Go to Solution Explorer -> Right click App_Data folder -> Add -> New item -> Select SQL Server database under Data -> Enter Database name -> Add.

Step 3

Create a table to store the data.

  1. Open Database ->Right click Table folder -> Add New Table -> Add Columns -> Save -> Enter table name -> OK.

  2. In this tutorial, I have created a table (Country) to store the country list that will appear in the auto suggestion list (This table contains CountryID and CountryName as columns).

Step 4

Add Entity Data Model.

  1. Go to Solution Explorer ->Right click Project name form Solution Explorer -> Add -> New item -> Select ADO.net Entity Data Model under data -> Enter model name -> Add.

  2. A popup window will come (Entity Data Model Wizard) -> Select Generate from database ->click Next.

  3. Chose your data connection -> select your database ->select Entity framework version(5.0 or 6.0) next -> select tables ->enter Model Namespace name->click Finish.

Step 5

Add Angular reference files,

  1. Add reference files in _Layout.cshtml page, given below. (You can download the files from angucomplete-alt.css and angucomplete-alt.js.

  2. Add these files in <head> tag.
    1. <!--Angualr refrence file for auto complete text box starts->  
    2. <script src="~/Scripts/angular.min.js"></script>  
    3. <script src = "~/Scripts/angular-route.min.js" > < /script>   
    4. <script src = "~/Scripts/angucomplete-alt.js" > < /script>   
    5. <link href = "~/Content/angucomplete-alt.css" rel = "stylesheet" / >  
    6. <script src = "~/Scripts/app.js" > < /script>  
    7. <!--Angualr refrence file for auto complete text box starts->  

Step 6

Add Controller.

  1. Add Controller by right clicking on Controllers folder -> Add -> Controller ->name it as Home Controller.

  2. Replace the code with the code, given below:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. namespace AngularAutoCompleteTextbox.Controllers  
    7. {  
    8.     public class HomeController: Controller  
    9.     {  
    10.         public ActionResult Index()  
    11.         {  
    12.             return View();  
    13.         }  
    14.         public ActionResult getAllCountries()  
    15.         {  
    16.             using(DatabaseEntities db = new DatabaseEntities())  
    17.             {  
    18.                 var countrylist = db.Countries.OrderBy(a => a.CountryName)  
    19.                     .ToList();  
    20.                 return new JsonResult  
    21.                 {  
    22.                     Data = countrylist, JsonRequestBehavior = JsonRequestBehavior.AllowGet  
    23.                 };  
    24.             }  
    25.         }  
    26.     }  
    27. }  
  3. Index action is used to render the view.

  4. getAllCountries method gets the data from the database and sends it to the Angular Controller in JSON format.

Step 7

Add Angular scripts to project.

  1. Right click Scripts folder -> Add JavaScript file (I named it app.js).

  2. Replace it with the code, given below:
    1. var app = angular.module('myapp', ['angucomplete-alt']); //add angucomplete-alt dependency in app  
    2. app.controller('AutoCompleteController', ['$scope''$http', function ($scope, $http) {  
    3.     $scope.Countries = [];  
    4.     $scope.SelectedCountry = null;  
    5.     //event fires when click on textbox  
    6.     $scope.SelectedCountry = function (selected) {  
    7.         if (selected) {  
    8.             $scope.SelectedCountry = selected.originalObject;  
    9.         }  
    10.     }  
    11.     //Gets data from the Database  
    12.     $http({  
    13.         method: 'GET',  
    14.         url: '/Home/getAllCountries'  
    15.     }).then(function (data) {  
    16.         $scope.Countries = data.data;  
    17.     }, function () {  
    18.         alert('Error');  
    19.     })  
    20. }]);  
  3. Here $scope.SelectedCountry stores the selected value in the text box. $http Service gets the data from the Server.

Step 8

Add view to display UI.

  1. Right click Index action -> Add View -> name it -> Click Add.

  2. Replace the code with the code given below in Index.cshtml page.
    1. @{  
    2.     ViewBag.Title = "Mitechdev.com";  
    3. }  
    4. <div class="container">  
    5.     <h2>Autocomplete textbox in AngularJS</h2>  
    6.     <div ng-app="myapp">  
    7.         <div ng-controller="AutoCompleteController">  
    8.             <div angucomplete-alt id="txtAutocomplete" placeholder="Type country name" pause="100"  
    9.                  selected-object="SelectedCountry" local-data="Countries" search-fields="CountryName"  
    10.                  title-field="CountryName" minlength="1" input-class="form-control" match-class="highlight">  
    11.             </div>  
    12.             <!--display selected country-->  
    13.             <div ng-show="SelectedCountry">  
    14.                 Selected Country : {{SelectedCountry.CountryName}}  
    15.             </div>  
    16.         </div>  
    17.     </div>  
    18. </div>  
  3. In div element, we must add angucomplete-alt. We bind the data, using the local-data attribute.

  4. After running the Application, we will get our result.
Note: For related articles on angularjs application development visit Angular Js Series.

Conclusion

I hope this article may help you in understanding how to implement an auto complete textbox using Angular JS in MVC 5. If you want to make any suggestions, please contact me.Please find the original source and download source code from here Autocomplete textbox using Angularjs.


Similar Articles