Search code examples
javascriptangularjstwitter-bootstraptypeahead.jsangular-ui-typeahead

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?


Solution

  • 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.