Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching in two fields using Bootstrap Typeahead in AngularJS

I have two fields in my JSON: first_name and last_name.

I want to use Bootstrap typeahead.js, using Angular-UI.

<script type="text/ng-template" id="customTemplate.html">
  <a>
    <span bind-html-unsafe="match.label | typeaheadHighlight:query"></span>
  </a>
</script>
  <input type="text" ng-model="result" typeahead="patient as patient.first_name for patient in ngGridUsersData.patients | filter:{first_name:$viewValue}" typeahead-template-url="customTemplate.html">

What would I add in the typeahead field to search also in last_name? What would I add in the template to display both the first and last name upon selection?

If the angular-ui directive doesnt have this functionality, then I guess I'll just concatenate the first and last name into one string.

UPDATE: 9/15/14 Any idea how to display the first and last name in the search results?

like image 503
achabacha322 Avatar asked Feb 13 '23 02:02

achabacha322


2 Answers

You can try using a custom function for the typeahead, instead of using the filter:

<input type="text" 
       ng-model="result" 
       typeahead="patient as patient.first_name for patient in filterByName(ngGridUsersData.patients, $viewValue)" 
       typeahead-template-url="customTemplate.html">

// ...snip...

function filterByName(patients, typedValue) {
    return patients.filter(function(patient) {
        matches_first_name = patient.first_name.indexOf(typedValue) != -1;
        matches_last_name = patient.last_name.indexOf(typedValue) != -1;

        return matches_first_name || matches_last_name;
    });
}
$scope.filterByName = filterByName;

Caveat: I haven't tested this code/yanked it from a project of mine, so there might be one or two errors that require some tweaking to fix.

like image 128
Michael0x2a Avatar answered Feb 14 '23 14:02

Michael0x2a


To display both the first name and last name in the search results amend michael0x2a's input markup to read:

 <input type="text" 
       ng-model="result" 
       typeahead="patient as patient.first_name + ' ' + patient.last_name for patient in filterByName(ngGridUsersData.patients, $viewValue)" 
       typeahead-template-url="customTemplate.html">
like image 26
nothingman Avatar answered Feb 14 '23 16:02

nothingman