DotNetSlackers: ASP.NET News for lazy Developers

Friday, October 16, 2015

Create Facebook style autocomplete in AngularJS with MVC

To achieve this, you need to include following libraries.

AngularJS
ui-bootstrap-tpls
Now Let’s create.
Step 1- Create a new empty MVC project.

Step 2- Add a Home Controller.

Step 3- Add a Index view.

Write the following code to your index view.
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<html ng-app="myApp">
<head>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/ui-bootstrap-tpls.min.js"></script>
    <script src="~/Scripts/AutoCompleteDemo.js"></script>
    <link href="~/Css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div ng-controller="myCtrl" class="row-fluid">
            <form class="row-fluid">
                <div class="container-fluid">
                    Code <input type="text" ng-model="selectedCode" />
                    City <input type="text" typeahead-on-select="setcode($item)" ng-model="selected" typeahead="Cityx.CityName for Cityx in City | filter:$viewValue" />
                </div>
            </form>
        </div>
    </div>
</body>
</html>
 
Here we are binding typeahead directive to our input field.

Step 4- Now create a js file and name it as AutoCompleteDemo.

Write the following code to it.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
angular.module('myApp', ['ui.bootstrap'])
    .controller("myCtrl", function ($scope) {
        $scope.selected = '';
        $scope.City = [
                    { code: 'JP', CityName: 'Jaipur' },
                    { code: 'DL', CityName: 'Delhi' },
                    { code: 'CHE', CityName: 'Chennai' },
                    { code: 'MUM', CityName: 'Mumbai' },
                    { code: 'KOL', CityName: 'Kolkata' },
                    { code: 'MAS', CityName: 'Chennai' },
                    { code: 'JAM', CityName: 'Jammu' },
                    { code: 'MAS', CityName: 'Chennai' },
                    { code: 'KAN', CityName: 'Kanpur' },
        ];
       $scope.setcode = function (selection) {
            $scope.selectedCode = selection.code;
        };
});
In above code.

a) First Inject the dependency on ui.bootstrap module.

b) Create sample list of city with their code to see AutoComplete.

DEMO
Autocomplete In angularJS with VC
DOWNLOAD

No comments:

Post a Comment