Skip to content

Instantly share code, notes, and snippets.

@lucianprecup
Created July 3, 2013 16:19
Show Gist options
  • Save lucianprecup/5920014 to your computer and use it in GitHub Desktop.
Save lucianprecup/5920014 to your computer and use it in GitHub Desktop.
jquery angularjs autocomplete elasticsearch
angular.module('esClient.autocomplete', []).
directive('autoComplete', ['$http', function($http) {
return function (scope, elmt, attrs) {
$(function () {
$(elmt).autocomplete({
minLength:1,
html:true,
source:function (request, response) {
var postData = {
"fields": [
"id",
"nom",
"lieux" ],
"query": {
"query_string": {
"fields": [
"nom",
"lieux"
],
"query": request.term,
"use_dis_max": false,
"auto_generate_phrase_queries": true,
"default_operator": "OR"
}
},
"highlight": {
"number_of_fragments": 0,
"pre_tags": ["<b>"],
"post_tags": ["</b>"],
"fields": {
"nom": {},
"lieux": {}
}
}
};
$.ajax({
url: "http://localhost:9200/bzh/personne/_search",
type: "POST",
dataType: "json",
data: JSON.stringify(postData),
success: function( data ) {
response( $.map( data.hits.hits, function( item ) {
return {
label: (item.fields["nom"] ? (item.highlight["nom"] ? item.highlight["nom"] : item.fields["nom"]) + " " : "")
+ (item.fields["lieux"] ? (item.highlight["lieux"] ? item.highlight["lieux"] : item.fields["lieux"]): ""),
ck: (item.fields["nom"] ? item.fields["nom"] : ""),
id: item.fields["id"]
}
}));
}
});
},
focus:function (event, ui) {
elmt.val(ui.item.ck);
return false;
},
select:function (event, ui) {
scope.$apply;
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" ).html( item.label ) )
.appendTo( ul );
};
});
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment