autocomplete

by sjmcpherson

HTML

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<div ng-app='MyModule'>
    <div ng-controller='DefaultCtrl'>
        <div contenteditable="true" auto-complete ui-items="names" ng-model="selected"></div>
        selected = {{selected}}
    </div>
</div>

CSS

div[contenteditable]{
    display: block;
    border: 1px solid #ccc;
    width:400px;
    padding:2p 5px;
}
div[contenteditable]:hover{
    background-color:#eee;
      border: 1px solid #ddd;  
}
div[contenteditable]:focus{
            display: block;
            border: 1px solid blue;   
 }

	.ui-autocomplete {
		max-height: 100px;
		overflow-y: auto;
		/* prevent horizontal scrollbar */
		overflow-x: hidden;
	}
	/* IE 6 doesn't support max-height
	 * we use height instead, but this forces the menu to always be this tall
	 */
	* html .ui-autocomplete {
		height: 100px;
	}

JavaScript

function DefaultCtrl($scope) {
    $scope.names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];
}

angular.module('MyModule', []).directive('contenteditable', function() {
	var tabIndex = 0;
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      // view -> model
	 tabIndex = tabIndex+1;
	  elm.attr('tabIndex',tabIndex);
	  
      elm.bind('blur', function() {
        scope.$apply(function() {
          ctrl.$setViewValue(elm.html());
        });
      });
	  scope.tabIndex = 0
	  
	  if(!attrs.textarea){	
		  elm.bind('keydown', function(e) {
			   if (e.keyCode == 13) {
				  //submit = true;
				  e.preventDefault();
				}
		  });
	  }

      // model -> view
      ctrl.$render = function() {
        elm.html(ctrl.$viewValue);
      };
    }
  };
}).directive('autoComplete', function($timeout) {
    return function(scope, elm, attrs, ctrl) {
            elm.autocomplete({
                source: scope[attrs.uiItems],
                select: function() {
                    $timeout(function() {
                      elm.trigger('div');
                    }, 0);
                }
            });
    };
});