如何使用typeahead属性为文本框设置初始值?

How to est initial value to the text box with typeahead attribute?

我在 angularjs 项目中使用 typeahead。

我要将此值显示在具有 typeahead 属性的文本框中:

  $scope.cities = [{id:1,address:'Berlin'},
                   {id:2,address:'Bonn'},
                   {id:3,address:'London'},
                   {id:4,address:'Miami'}];

这里是带有 typeahead 属性的输入文本框:

<input type="text" 
ng-model="city" 
typeahead-input-formatter="inputFormatter($model)"
placeholder="Custom template"  
uib-typeahead="city as city.address for city in cities | filter:$viewValue"
class="form-control"  
typeahead-show-hint="true" 
typeahead-min-length="0"/>

这里是plunker.

如何为城市的文本框设置初始值,例如 id=3。

如果您需要设置默认的选定值,那么您可以为您的模型分配一个值 $scope.city(在 HTML 中您有 <input type="text" ng-model="city" ..),像这样:

$scope.selected = {id:1, address:'Berlin'};
$scope.cities = [{id:1, address:'Berlin'},
                              {id:2,address:'Bonn'},
               {id:3,address:'London'},
               {id:4,address:'Miami'}];
//assign model value
$scope.city =  $scope.cities[3]   
//or do like this - $scope.city =  $scope.selected;

检查插件:http://plnkr.co/edit/zKkIbyGYetxQejyfBSnG?p=preview

如果不是按id排序,那么你仍然可以通过id找到它(假设你使用lodash,如果不是,你可以用Array.forEach):

var id_i_need = 42;
var defaultItem = _.find($scope.cities, function(item){
  return item.id == id_i_need;
})[0]
 $scope.city = defaultItem;