autocomplete

autocomplete features

by Samar Pattanayak

HTML

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app='myModule'>
  <div ng-controller='myController'>
    From :
    <input type="text" class="txtClass" ng-model="val" my-directive/> 
    To :
    <input type="text" class="txtClass" ng-model="val1" my-directive/>

  </div>
</div>

CSS

.txtClass {
  border-radius: 5px;
  border-color: green;
  margin: 5px 15px 0px 3px;
}

JavaScript

var app = angular.module("myModule", [])
  .controller("myController", function($scope) {
    $scope.names = ['apples', 'oranges', 'bananas', 'ora', 'oral', 'ourrrrrrrrrr'];
    $scope.newItem = [{
      label: 'samar',
      id: 3
    }, {
      label: 'samar1',
      id: 32
    }, {
      label: 'samar2',
      id: 33
    }]
  })
  .factory("myFactory", function() {
    return {
      getSource: function() {
        return [{
          label: 'Bangalore',
          id: 3
        }, {
          label: 'Bhubaneswar',
          id: 32
        }, {
          label: 'Delhi',
          id: 32
        }, {
          label: 'Deradhun',
          id: 33
        }, {
          label: 'Bhopal',
          id: 34
        }, {
          label: 'Bombay',
          id: 35
        },{
          label: 'Bhutan',
          id: 36
        },{
          label: 'Chennai',
          id: 36
        },{
          label: 'Hyderabad',
          id: 37
        }];
      }
    }
  })
  .directive("myDirective", function(myFactory) {
    return {
      restrict: 'EA',
      require: 'ngModel',
      link: function(scope, elem, attr, ctrl) {
        // elem is a jquery lite object if jquery is not present,
        // but with jquery and jquery ui, it will be a full jquery object.
        //debugger
        elem.autocomplete({
          //source: scope.newItem, //from your service
          source: myFactory.getSource(),
          minLength: 1,
          select: function(e, ui) {
            event.preventDefault();
            console.log(e.type + ui.item.id);
            debugger;
            attr.$set('value', ui.item.id);
          },
          focus: function(event, ui) {
            event.preventDefault();
            console.log(ui.item.id + ' ,' + event.type);
          }
        });
      }
    }
  })