Search code examples
javascripthtmlangularjsangular-strap

Angular ng-options behaves odd


I have this typahead with angular strap:

<div class="form-group" ng-class="newGroupForm.placeReference.$invalid ? 'has-error' : ''">
    <label for="placeReference" class="col-lg-2 control-label">Group Location</label>
    <div class="col-lg-10">
        <input type="text" name="placeReference" 
               ng-model="newGroup.reference" 
               ng-options="place.reference as place.name 
                           for place in getPlaces($viewValue)" 
               bs-typeahead min-length="0" required >
    </div>
</div>

getPlaces returns array of objects which looks like this:

{
   reference: "ccj32213SIJD",
   name: "some name",
}

When I am typing I am getting correct results, but when I select the wonted option the value that I see in my input is the reference (instead of the name).

Can any one point out my mistake?

suggestions reference instead of name

Here is the controller code:

$scope.getPlaces = function(viewValue) {
    var input = viewValue || $scope.currentPlace;
    return googleService.placesAutocomplete(input).then(
        function(places) {
            return places;
        }
    );
};

Solution

  • If ng-options here behaves exactly like <select ng-options> (sorry, I'm not familiar with bs-typeahead directive), then you should change it to:

    <input ... 
        ng-model="selectedPlace" 
        ng-options="place as place.name for place in getPlaces($viewValue)">
    

    Then you can use get the name elsewhere:

    <div>{{selectedPlace.name}}</div>
    

    It's probably best to get the actual place object {name: "..", reference: "..."}, but if you just need the name, then you could do this:

    <input ... 
            ng-model="selectedPlaceName" 
            ng-options="place.name as place.name for place in getPlaces($viewValue)">