Created
August 2, 2016 07:02
-
-
Save jovanialferez/6d565b69cc326964fbc8181d8d3c6526 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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