Skip to content

Instantly share code, notes, and snippets.

@jovanialferez
Created August 2, 2016 07:02
Show Gist options
  • Save jovanialferez/6d565b69cc326964fbc8181d8d3c6526 to your computer and use it in GitHub Desktop.
Save jovanialferez/6d565b69cc326964fbc8181d8d3c6526 to your computer and use it in GitHub Desktop.
function myAutocomplete ($document, $timeout, $compile) {
return {
restrict: 'A',
scope: {
onSelectModel: '='
},
template: require('./autocomplete.html'),
transclude: true,
link: (scope, element, attrs) => {
$document.ready(() => {
// list of items for suggestions/autocompletion
let sources = JSON.parse(attrs.source);
// add class to container to have its onw isolated styling (css)
// not to affect other elements on the page
element.addClass('autocomplete-container');
// local method (called thru ng-click) to mark current selected item from the suggested list
scope.selected = (item) => {
console.log('selected', item);
scope.onSelectModel = item;
scope.matches = [];
}
// filter the current list (sources) for every key pressed
// and returning the matching items (case-insensitive, any position)
angular.element(element[0].querySelector('input')).bind('keyup', (e) => {
scope.matches = sources.filter((item) => {
if (e.target.value === '') return false;
if (item.toLowerCase().indexOf(e.target.value.toLowerCase()) !== -1) return true;
return false;
});
})
}) // document.ready
}
}
}
export default angular.module('app.directives.myAutocomplete', [])
.directive('myAutocomplete', myAutocomplete)
.name;
<div ng-transclude></div>
<ul class="list autocomplete-list">
<li class="item" ng-repeat="item in matches" ng-click="selected(item)">{{ item }}</li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment