Skip to content

Instantly share code, notes, and snippets.

@ahoereth
Last active December 30, 2015 12:29
Show Gist options
  • Save ahoereth/7829487 to your computer and use it in GitHub Desktop.
Save ahoereth/7829487 to your computer and use it in GitHub Desktop.
Highly unobtrusive typeahead directive for AngularJS: ngxSouffleur
.ngx-souffleur {
position: relative;
}
.ngx-souffleur div,
.ngx-souffleur input {
position: absolute;
top: 0;
left: 0;
}
.ngx-souffleur div {
color: #ccc;
}
.ngx-souffleur input {
background-color: transparent;
}
(function () {
/**
* Highly unobtrusive typeahead directive:
* <ngx-souffleur src ng-model event child-class input-id>
*/
var ngxSouffleur = function () {
return {
restrict: 'E',
replace: true,
scope: {
model: '=ngModel',
event: '=',
class: '@childClass',
id: '@inputId',
src: '='
},
controller: function($scope) {
$scope.souffleur = '';
/* *
* Is triggered on every keypress and reacts to keyCode 9 ("tab") only.
* Checks if the souffleur is currently suggesting something, if so fills it in
* and triggers the specified event.
*/
$scope.keydown = function( $event ) {
if ( typeof $scope.model === 'undefined' ||
$scope.souffleur === $scope.model ||
$scope.souffleur === '' ||
$scope.model === '' ||
$event.keyCode != 9 ||
$event.shiftKey ) return;
$event.preventDefault();
$scope.model = $scope.souffleur;
};
/* *
* Watch the model and look for an appropriate suggestion in the specified source array.
*/
$scope.$watch('model', function(n, o) {
$scope.souffleur = '';
if ( typeof input === 'undefined' || typeof $scope.src === 'undefined' || input === '' )
return;
for ( var i = 0, len = $scope.src.length; i < len; i++ ) {
if ( ($scope.src[i] + '').substring(0, input.length).toLowerCase() == input.toLowerCase() )
return $scope.souffleur = input + ($scope.src[i] + '').substring(input.length);
}
});
},
template:
'<div class="ngx-souffleur">'+
'<div class="{{class}}">{{souffleur}}</div>'+
'<input type="text" class="{{class}}" id="{{id}}" ng-model="model" ng-keydown="keydown($event)">'+
'</div>'
};
};
angular.module('myModule').directive('ngxSouffleur', ngxSouffleur);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment