Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a value from typeahead shows Objec object

I am working on Single Page Application and using Angular-TypeAhead when i write something in textbox it shows me suggestions but when i select the suggestion then the values of Textbox become Object object instead of name

here is my HTML Markup

<div class="bs-example" style="padding-bottom: 24px;" append-source>
    <form class="form-inline" role="form">
      <div class="form-group">
        <label><i class="fa fa-globe"></i> State</label>
        <input type="text" class="form-control" ng-model="selectedState" ng-options="state.FirstName for state in states" placeholder="Enter state" bs-typeahead>
      </div>
    </form>
  </div>

and here is my AngularJS code

var app = angular.module('mgcrea.ngStrapDocs', ['ngAnimate', 'ngSanitize', 'mgcrea.ngStrap'])

        .controller('TypeaheadDemoCtrl', function ($scope, $templateCache, $http) {

            $scope.selectedState = '';

            $http.get('/api/servicesapi/GetAllClients')
            .then(
                function (result) {
                    //success
                    $scope.states = result.data;
                },
                function () {
                    //error
                });

        });

see the images here

enter image description hereenter image description here

like image 557
Mohsin Avatar asked Mar 21 '14 11:03

Mohsin


2 Answers

Change ng-options="state.FirstName for state in states" to ng-options="state as state.FirstName for state in states"

like image 156
L42y Avatar answered Oct 21 '22 10:10

L42y


This is the solution in Angular 4 and not angularJS

I added [inputFormatter]="formatMatches" to format the input (ngmodel) and [resultFormatter]="formatMatches" to format the data displayed

<input id="typeahead-format" type="text" [(ngModel)]="clickedItem" 
    name="profile" (selectItem)="selectedItem($event)"
   [resultFormatter]="formatter" [inputFormatter]="formatter"
   [ngbTypeahead]="search" #instance="ngbTypeahead"/>

and the formatter function is like this:

formatter = (x: { label: string }) => x.label;

x: is the object

like image 26
Ghizlane Lotfi Avatar answered Oct 21 '22 11:10

Ghizlane Lotfi