Bish25
Bish25

Reputation: 616

Angularjs Typeahead not showing dropdown

i am trying to use an async typeahead, i can get the data fine and the inspector clearly shows data being returned. for example i am using the bootstrap example of getLocation

$scope.getLocation = function(val) {
    return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
      params: {
        address: val,
        sensor: false
      }
    }).then(function(response){
      return response.data.results.map(function(item){
        return item.formatted_address;
      });
    });
  };

this works exactly how i want it to work and then this is my approach.

$scope.filterClients =function(val) {
        var data = $.param({
            action: "filter_clients",
            value: val
        });
        var config = {headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}}

        $http.post('http://***************.co.uk/switchboard.php', data, config)
            .then(function (response) {
                return response.data.map(function(item){
                    return item.first_name;
                  });
            });  
    };

HTML CODE

<input ng-model="asyncSelected" placeholder="Select a Client" uib-typeahead="first_name for first_name in filterClients($viewValue)" class="form-control"/>

Upvotes: 0

Views: 332

Answers (1)

codtex
codtex

Reputation: 6548

You don't return anything from $scope.filterClients. Just change your function like this :

$scope.filterClients = function (val) {
    var data = $.param({
        action: "filter_clients",
        value: val
    });
    var config = {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}}

    return $http.post('http://***************.co.uk/switchboard.php', data, config)
            .then(function (response) {
                return response.data.map(function (item) {
                    return item.first_name;
                });
            });
};

NOTE

It is good to make sure that everything went fine before returning the data, otherwise you can get errors. Try something like this to avoid errors:

return $http.post('http://***************.co.uk/switchboard.php', data, config).then(function (response) {
    if (!angular.isObject(response) || !angular.isDefined(response.data)) {
        /* this you can put to avoid any errors */
        return;
    }

    /* if you want to limit you can use this code */
    var limit = 10;
    var data = [];
    for (var i = 0; i < response.data.length; i++) {
        if (i == limit) {
            break;
        }
        data.push(response.data[i]);
    }

    return data;
});

Upvotes: 1

Related Questions