Skip to content

Instantly share code, notes, and snippets.

@signalpoint
Last active January 25, 2016 21:32
Show Gist options
  • Save signalpoint/f30a9fc7e9612e147f6e to your computer and use it in GitHub Desktop.
Save signalpoint/f30a9fc7e9612e147f6e to your computer and use it in GitHub Desktop.
AngularJS Autocomplete with Drupal 8
'use strict';
angular.module('angularDrupalApp', ['my-module']).
run(function() {
// Typical app stuff here...
});
angular.module('my-module',[]).directive('autoComplete',['$http',function($http){
return {
restrict:'AE',
scope:{
},
templateUrl:'/autocomplete-template.html',
link:function(scope,elem,attrs){
scope.suggestions=[];
scope.selectedIndex=-1; //currently selected suggestion index
scope.search=function(){
$http.get(attrs.url+'?title='+scope.searchText).success(function(data){
console.log(data);
if(data.indexOf(scope.searchText)===-1){
data.unshift(scope.searchText);
}
scope.suggestions=data;
scope.selectedIndex=-1;
});
}
scope.checkKeyDown=function(event){
if(event.keyCode===40){//down key, increment selectedIndex
event.preventDefault();
if(scope.selectedIndex+1 !== scope.suggestions.length){
scope.selectedIndex++;
}
}
else if(event.keyCode===38){ //up key, decrement selectedIndex
event.preventDefault();
if(scope.selectedIndex-1 !== -1){
scope.selectedIndex--;
}
}
else if(event.keyCode===13){ //enter pressed
scope.resultClicked(scope.selectedIndex);
}
}
scope.resultClicked=function(index){
alert('you selected: ' + scope.suggestions[index].nid);
scope.searchText='';
scope.suggestions=[];
}
}
}
}]);
<div class="tags-wrapper">
<div id="tagsList" class="tags-cloud">
<input type="text" placeholder="Start typing" id="searchInput" ng-keydown="checkKeyDown($event)" class="form-control" ng-model="searchText" ng-change="search()"/>
</div>
<ul id="suggestions" class="suggestions-list">
<li ng-repeat="suggestion in suggestions" class="blockSpan" ng-click="resultClicked($index)" ng-mouseover="$parent.selectedIndex=$index" ng-class="{active : selectedIndex===$index}">{{suggestion.title}}</li>
</ul>
</div>
.active {
color: red;
}
<!-- include in the <head> -->
<link rel="stylesheet" type="text/css" href="autocomplete.css">
<!-- include somewhere in your app's <body> as a directive -->
<div auto-complete url="/drupal/api/course-locator.json" model="data.tags"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment