20

I have the following Angular UI-Bootstrap typeahead working great:

<input class="span2" type="text" ng-model="selectedStuff" typeahead="stuff as stuff.name for stuff in stuffs | filter:$viewValue"/>

Though, it's almost working too great. I'm able to display the stuffs.name for the purposes of the typeahead AND select the full stuff object in stuffs. The problem is that my $viewValue is matching all of the properties in stuff instead of just the stuff.name. I've tried adding the .name to various places in the typeahead with no luck. Is there a straightforward way to display and match only the .name but still return the entire object?

Jesse
  • 2,043
  • 9
  • 28
  • 45

1 Answers1

38

The typeahead directive from the http://angular-ui.github.io/bootstrap/ repo was build to well fit into existing AngularJS ecosystem. This means that this directive tries to re-use as much as possible of syntax, filters and directives already used in AngularJS.

Back to your question - the filtering itself is done by the Angular's filter filter described here: http://docs.angularjs.org/api/ng.filter:filter The mentioned filter's syntax is flexible enough to limit searches to a selected set of properties:

typeahead="stuff as stuff.name for stuff in stuffs | filter:{name: $viewValue}"

Please notice: filter:{name: $viewValue}

Working plunk here: http://plnkr.co/edit/o1qWKq8LSmbbmVaYkOvb?p=preview

Mo.
  • 26,306
  • 36
  • 159
  • 225
pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
  • Thank you very much! I swear I've been trying to RTFM, but I guess I'm going to have a to keep at it. – Jesse Apr 18 '13 at 11:46
  • I don't see the difference that `filter: {name: $viewValue }` I tried changing it to `filter: $viewValue` and the output was the same. – Saad Farooq Jul 01 '13 at 05:45
  • @SaadFarooq When you change the syntax t `filter: $viewValue`, angular basically creates a JSON string out of the object and searches that. The syntax pkozlowski used searches ONLY the name field. Test using the word "second" on the Plnkr above. It appears no where in the name fields. If you edit it as you've suggested, then "second" would show the 2nd result. – jklemmack Nov 04 '13 at 23:11