Typeahead对象数组?

时间:2015-01-21 02:04:32

标签: angularjs angular-ui angular-ui-typeahead

我在理解AngularUI Bootstrap的Typeahead指令时遇到了一些问题。在他们的statesWithFlags对象数组的例子中,它们不一定解释指令表达式的含义。

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

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

他们使用州两次,有人可以向我解释一下吗?除了解释过滤器究竟是什么意思?

例如,当我尝试使用一个对象数组创建一个对象并使用Typeahead查看该数据时,我似乎无法访问任何数据。

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}">

1 个答案:

答案 0 :(得分:13)

此typeahead表达式与ngSelect上的ngOptions语法相同(此博客上的详细信息:http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/)。

基本上是列表理解。您将提供用于填充选项的typeahead列表,用于在选择时设置模型值的对象以及应如何显示该选项,使用以下语法:

modelValue as display for iterationItem in list

你的问题是“in dataExample”部分想要一个数组,但是你给它一个对象(你可以给它一个对象,但这不是你想要做的)。你想要:

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

至于你的另一个问题,过滤器只是过滤了typeahead应该显示的选项。 $ viewValue是属性typeahead设置,无论用户输入什么,过滤器将只选择与该子字符串匹配的选项。

相关问题