Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead Array of Objects?

I am having some issues understanding AngularUI Bootstrap's Typeahead directive. In their example of the statesWithFlags array of objects, they do not necessarily explain what the directive expression is saying.

state as state.name for state in statesWithFlags | filter:{name:$viewValue}

Link: http://angular-ui.github.io/bootstrap/#/typeahead

They use state twice, may someone explain this to me? As well as explain what exactly the filter is saying?

Example, when I try creating an object with an array of objects and go over that data with Typeahead, I cannot seem to access any of the data.

JSON

$scope.dataExample = {
  'students' : [
    {
      'id': 1,
      'name': 'John Doe'
    },
    {
      'id': 2,
      'name': 'Jane Doe'
    }
  ]
};

HTML

<input type="text" ng-model="selectedStudent" typeahead="student as students.name for student in dataExample | filter:{name:$viewValue}">
like image 400
Aaron Brewer Avatar asked Jan 21 '15 02:01

Aaron Brewer


1 Answers

This typeahead expression is the same syntax as ngOptions on ngSelect (more info on this blog: http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/).

It's essentially list comprehension. You're providing a list for typeahead to use to populate the options, the object to set the model value to when selected, and how the option should be displayed, with the following syntax:

modelValue as display for iterationItem in list

Your problem is that the "in dataExample" part wants an array, but you're giving it the object (you can give it an object, but this isn't what you're trying to do). You want:

<input type="text" ng-model="selectedStudent" typeahead="student as student.name for student in dataExample.students | filter:{name:$viewValue}">

As for your other question, the filter is just filtering what options typeahead should show. $viewValue is a property typeahead sets to whatever the user has typed in, the filter will select only the options that match that substring.

like image 92
David Williams Avatar answered Nov 04 '22 19:11

David Williams