Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Angular Typeahead,其中模型作为数组对象的Id,文本作为数组对象的名称_Javascript_Angularjs_Typeahead - Fatal编程技术网

Javascript Angular Typeahead,其中模型作为数组对象的Id,文本作为数组对象的名称

Javascript Angular Typeahead,其中模型作为数组对象的Id,文本作为数组对象的名称,javascript,angularjs,typeahead,Javascript,Angularjs,Typeahead,我正在使用。那么,您能告诉我如何将模型设置为id并将文本显示为名称。我已经尝试了下面的方法。但它不起作用。我该怎么做?谢谢 注意:请在下面的代码笔上键入a或k,对其进行测试 JS var states=[{'id':1,'name':'Alabama'},{'id':2,'name':'Kansas'}] Html <input name="states" id="states" type="text" placeholder="enter a state" ng- mode

我正在使用。那么,您能告诉我如何将
模型
设置为
id
并将
文本
显示为
名称
。我已经尝试了下面的方法。但它不起作用。我该怎么做?谢谢

注意:请在下面的代码笔上键入
a
k
,对其进行测试

JS

 var states=[{'id':1,'name':'Alabama'},{'id':2,'name':'Kansas'}]
Html

    <input name="states" id="states" type="text" placeholder="enter a state" ng-
model="selected" typeahead="a.id as a.name for a in states | filter:$viewValue" 
class="form-control">

问题是,当您尝试仅将所选状态
id
放入
ng model
中时,它将仅在该输入字段中显示所选状态的
id
,因为
ng model
中只有
id

因此,基本上您必须选择整个对象,而不是将id放入
ng model
。当选择任何状态作为.name时,
a将仅从表达式中显示
name
。只要您想通过state
id
,就可以使用
selected.id

标记

<div class="form-group">
  <label for="states">Search for US States</label>
  <pre>Model: {{selected | json}}</pre>
  <input name="states" id="states" type="text" 
     placeholder="enter a state" ng-model="selected" 
     typeahead="a as a.name for a in states | filter:$viewValue" 
     class="form-control">
</div>

搜寻美国各州
模型:{selected | json}

问题是,当您尝试仅将所选状态
id
放入
ng model
中时,它将仅在该输入字段中显示所选状态的
id
,因为
ng model
中只有
id

因此,基本上您必须选择整个对象,而不是将id放入
ng model
。当选择任何状态作为.name时,
a将仅从表达式中显示
name
。只要您想通过state
id
,就可以使用
selected.id

标记

<div class="form-group">
  <label for="states">Search for US States</label>
  <pre>Model: {{selected | json}}</pre>
  <input name="states" id="states" type="text" 
     placeholder="enter a state" ng-model="selected" 
     typeahead="a as a.name for a in states | filter:$viewValue" 
     class="form-control">
</div>

搜寻美国各州
模型:{selected | json}

非常感谢。一个问题是:当我从列表中选择一个项目时,它工作正常。但是当我尝试键入一个不存在的项目时,
模型就不能作为对象工作。它显示如下:
选中:“wsdef”
。有没有办法显示它也是这样的:
选中:id:null,name:“wsdef”
还是像其他场景一样作为对象?谢谢。非常感谢。一个问题是:当我从列表中选择一个项目时,它工作得很好。但是当我尝试键入一个不存在的项目时,
模型
就不能作为对象工作。它显示如下:
选中:“wsdef”
。有没有办法显示它也是这样的:
选中:id:null,name:“wsdef”
还是像其他场景一样作为对象?谢谢