Get id and name on typehead

110 views Asked by At

I can return the name and id but i only can print the name.

I have try with update and sfterslected

at the moment i have this code and works fine but i just get the name!

 $('input.typeahead').typeahead({
    source:  function (query, process) {
    return $.ajax({
    url: "search/autocomplete",
    type: "GET",
    data: "query=" + query,
    success: function(data) {

      var data = $.merge( $.merge( [], data['2'] ), data['1'] );
      return process(data); 
    }
    });

   }         
 });

The expeted result is get the name as it give and the id (the id should be printed at other div for exemple #mydiv

Thanks in advance!

2

There are 2 answers

0
José Neves On

The answer just add afterSelect

  $('input.typeahead').typeahead({
   source:  function (query, process) {
     return $.ajax({
     url: "search/autocomplete",
     type: "GET",
     data: "query=" + query,
     success: function(data) {

    var data = $.merge( $.merge( [], data['2'] ), data['1'] );

    return process(data); 

         // this returns an array checked with console
  }

});

},
 afterSelect: function(data){
    console.log(data.id);
}
 });
0
Ramya Iyer On

You can make a directive for typehead with bloodhound

app.directive('typeheadDirective', function() {
    return {
        restrict: 'A',
        scope: {
            themes: '=',
            output: '=',
        },
        link: function(scope, element, attrs) {
            var themes = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace('theme_name'),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                local: scope.themes,
            })
            element.typeahead(null, {
                name: 'themes',
                displayKey: function(item) {
                    return item.theme_name
                },
                source: themes.ttAdapter()
            })
            element.bind('typeahead:select', function(ev, theme) {
                scope.output = {
                    'id': theme.id,
                    /*'theme_id': theme.id,*/
                    'theme_name': theme.theme_name
                }
                // element.value = ''
                scope.$apply();
            })
        }
    };
});