I have input field which I am using for autocomplete and populate on the fly by executing http requests. I am getting such object as example:
{
id:1,
name:'ABC'
}
I want to display name for a end user but later on when input has been selected I want to use it as id in my further processing. But ng-model converts my object into the string and I loose my id.
In general all works fine but my issue is that when user select something, lets say string "ABC" it means nothing for me unless I can tied it to "ID" which has been returned by my API. Only if I know ID I can continue future processing.
Could you please help me to figure out, what should I do in order to capture fromSelected as object but still show friendly text to user?
Thanks for any help!
Code:
HTML:
<input type="text" ng-model="fromSelected" placeholder="Country, city or airport" typeahead="place.readableName for place in getPlace($viewValue, 'en')" typeahead-loading="loadingLocations" typeahead-no-results="noResults" class="form-control">
JS:
app.controller('PlaceController', function($scope, $http, searchData) {
$scope.fromSelected = '';
$scope.toSelected = '';
$scope.$watch('fromSelected', function(newValue, oldValue){
if (newValue !== oldValue) searchData.setTravelFrom(newValue);
});
$scope.$watch('toSelected', function(newValue, oldValue){
if (newValue !== oldValue) searchData.setTravelTo(newValue);
});
// Any function returning a promise object can be used to load values asynchronously
$scope.getPlace = function(term, locale) {
return $http.get('http://localhost:8080/api/places/search', {
params: {
term: term,
locale: locale
}
}).then(function(response){
return response.data.map(function(item){
return {
'id': item.id,
'name': item.name,
'readableName': item.name + ' (' + item.id + ')'
};
});
});
};
});
ng-model="fromSelected.name"and$scope.fromSelected = {}?searchData.setTravelFromhere?