AngularUI-Bootstrap's Typeahead Can't Read `length` Property of `undefined`

前端 未结 3 744
时光取名叫无心
时光取名叫无心 2020-12-31 03:07

I am getting the following error when I attempt to get a typeahead values from AngularUI-Bootstrap, using a promise.

TypeError: Cannot read property \'length         


        
相关标签:
3条回答
  • 2020-12-31 03:24

    $scope.getTypeaheadValues is not returning any array. It returns null, because your return statement is in the callback function "success", which is called asynchrony.

    Maybe this will work:

    $scope.getTypeaheadValues = function($viewValue)
    {    
        var output = [];
        $http({
            method: 'GET',
            url: 'api/v1/person?name__icontains=' + $viewValue
        }).error(function ($data) {
            console.log("failed to fetch typeahead data");
        }).success(function ($data) {            
            $data.objects.forEach(function (person)
            {
                output.push(person.name);
            });
            console.log(output);        
        });
        return output;
    }
    
    0 讨论(0)
  • 2020-12-31 03:32
    $scope.getTypeaheadValues = function($viewValue)
    {
        var someOutput="";//return something
    
        $http({
            method: 'GET',
            url: 'api/v1/person?name__icontains=' + $viewValue
        }).error(function (data) {
            console.error(data);
        }).success(function (data) {
            console.log(data);//Do whatever you want 
        });
    return someOutput;
    

    }

    //The return statement is missing

    0 讨论(0)
  • 2020-12-31 03:39

    This problem was two fold.

    The first is that I was not returning the promise event (the $http call). The lack of a return statement (as @tobo points out) is what was causing the error directly. I needed to be returning the promise though, not the array.

    The second is that I need to be using .then rather than .success for AngularUI-Bootstrap to pick up the results.

    I ran across the following question: How to tie angular-ui's typeahead with a server via $http for server side optimization?

    Which updated my function call to the below:

    $scope.getTypeaheadValues = function($viewValue)
    {
        return $http({
            method: 'GET',
            url: 'api/v1/person?name__icontains=' + $viewValue
        }).then(function ($response) {
            var output = [];
    
            console.log($data);
    
            $response.data.objects.forEach(function (person)
            {
                output.push(person.name);
            });
    
            console.log(output);
            return output;
        });
    }
    
    0 讨论(0)
提交回复
热议问题