Thursday, March 26, 2015

AngularJS : Autocompleting Multiple Values Into a Single Field

This is of course is not a invention, but thought of writing this post as it might help some one, some day.

The thing  I am trying to achieve is some thing like below (please ignore the styling!).
Basically it’s just a textbox giving us suggestions from predefined list of items. The important thing hers is the textbox can have multiple entries and for each item it’s giving us suggestions. So let’s see  how we can build something like this using AngularJS and jQuery.

Here I will be using a Visual Studio solution, and if you want to learn how you can create an ASP.NET Project Powered by AngularJS using Visual Studio, please refer the below article.

First I need to install jQuery-UI nuget package and include the references.

jQuery UI
<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery-ui-1.11.4.js"></script>

Once the reference to jQuery and jQuery UI libraries are added, let’s write some code in the AngularJS controller to define the list of suggestions and write a method to invoke jQuery autocomplete on a textbox.
app.controller('homeController', function ($scope) {
    $scope.availableTags = [
    function split(val) {
        return val.split(/,\s*/);
    function extractLast(term) {
        return split(term).pop();
    $scope.autoComplete = function () {
        .bind("keydown", function (event) {
            if (event.keyCode === $.ui.keyCode.TAB &&
              $(this).autocomplete("instance") {
            minLength: 0,
            source: function (request, response) {
                $scope.availableTags, extractLast(request.term)));
            focus: function () {
                return false;
            select: function (event, ui) {
                var terms = split(this.value);
                this.value = terms.join(", ");
                return false;

Basically you can find this code snippet in jQuery UI site and I just modified it for AngularJS. Now in the view/template, let’s just create an textbox and put it’s id as “txtTags” and kick off our “autoComplete” method in key up event.
<input type="text" id="txtTags" ng-keyup="autoComplete()" />

So that’s about it. If you want the full sample code, you can download it from my OneDrive.

Happy Coding.


No comments:

Post a Comment