You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS Typeahead:如何在selectTraining中获取选中对象?

AngularJS Typeahead 获取选中对象并绑定指定ngModel的解决方法

需求

使用AngularJS的typeahead组件,需实现两个目标:

  • 在selectTraining(...)方法中获取选中的完整trainingEntry对象
  • 保持ngModel绑定为training.topic

原代码

<input 
    type="text" 
    class="form-control" 
    data-ng-model="training.topic"
    typeahead="trainingEntry.topic as trainingEntry.topic + ' ' + trainingEntry.location + ' ' + trainingEntry.trainingTyp + ' von ' + trainingEntry.from + ' bis ' + trainingEntry.to for trainingEntry in findTrainingsOfInstitutionByTerm($viewValue) | limitTo:5" 
    typeahead-on-select="selectTraining(trainingEntry)" />

解决方法

将typeahead-on-select的参数替换为$item,$item代表选中的完整trainingEntry对象,同时原有的ngModel绑定逻辑不受影响(因为typeahead表达式中trainingEntry.topic as ...已经指定了绑定到ngModel的值为trainingEntry.topic)。

修改后代码

<input 
    type="text" 
    class="form-control" 
    data-ng-model="training.topic"
    typeahead="trainingEntry.topic as trainingEntry.topic + ' ' + trainingEntry.location + ' ' + trainingEntry.trainingTyp + ' von ' + trainingEntry.from + ' bis ' + trainingEntry.to for trainingEntry in findTrainingsOfInstitutionByTerm($viewValue) | limitTo:5" 
    typeahead-on-select="selectTraining($item)" />

内容的提问来源于stack exchange,提问作者quma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 21:42:02