Reputation: 13614
I use typeahead in my angularjs project.
I hava this value to be displayed in textbox with typeahead attribute:
$scope.cities = [{id:1,address:'Berlin'},
{id:2,address:'Bonn'},
{id:3,address:'London'},
{id:4,address:'Miami'}];
And here is input text box with typeahead attribute:
<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"/>
Here is plunker.
How can I set initial value to the text box where cities has for example id=3.
Upvotes: 3
Views: 1861
Reputation: 9993
If you need to set the default selected value, then you can assign a value to the model in your case it's $scope.city
(as in HTML you have <input type="text" ng-model="city" ..
) , like so:
$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;
Check the plunk: http://plnkr.co/edit/zKkIbyGYetxQejyfBSnG?p=preview
If it's not ordered by id, then you can still find it by id (supposing you use lodash, if not, you can do it with Array.forEach
):
var id_i_need = 42;
var defaultItem = _.find($scope.cities, function(item){
return item.id == id_i_need;
})[0]
$scope.city = defaultItem;
Upvotes: 3