引导程序AngularJS上的异步请求uib-typeahead

时间:2017-09-29 22:27:14

标签: angularjs twitter-bootstrap-3 angular-ui-bootstrap bootstrap-typeahead

我正在尝试在服务器端搜索用户输入的名称,并使用bootstrap 3 uib-typeahead提供建议,但是(尽管我将值硬编码为返回 - 用于测试目的),没有值返回到预先输入的下拉列表。我的猜测是,由于这是一个异步请求,所以在检索请求数据时已经返回了任何数据。

有什么方法可以从服务器端检索数据,而typeahead正在侦听?

$scope.test_search = function(test_name){
    var curr_url = '/plan/ajax/test/';

    var search_response =  $http.get(curr_url,{
        cache: true,
        params:{'name': test_name, 'csrfmiddlewaretoken': $cookies.csrftoken}
    }).then(function successCallback(response) {
        console.log(response.data);
        //return response.data;
        var test = [
            {country: "US", name : 'Alabama'}
        ];
        return test;

    }, function errorCallback(response) {
        alert('Error');
    });

},
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="col-lg-6">
    <pre>Model: {{new_ingredient_selected | json}}</pre>
    <input type="text"
           ng-model = "new_ingredient_selected"
           placeholder="test test"
           uib-typeahead="ingredient.name for ingredient in test_search($viewValue) |  filter:{name:$viewValue}"
           typeahead-loading="loadingLocations"
           typeahead-no-results="noResults"
           typeahead-on-select="onTypeaheadIngredientSelect($item, $label, $index)"
           typeahead-wait-ms ="400"
           class="form-control">

    <i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
    <div ng-show="noResults">
      <i class="glyphicon glyphicon-remove"></i> No Results Found
    </div>
</div>

1 个答案:

答案 0 :(得分:2)

test_search函数需要return语句:

$scope.test_search = function(test_name){
    var curr_url = '/plan/ajax/test/';

    var search_response =  $http.get(curr_url,{
        cache: true,
        params:{'name': test_name, 'csrfmiddlewaretoken': $cookies.csrftoken}
    }).then(function successCallback(response) {
        console.log(response.data);
        //return response.data;
        var test = [
            {country: "US", name : 'Alabama'}
        ];
        return test;

    }, function errorCallback(response) {
        alert('Error');
        //IMPORTANT
        //RE-THROW the error
        ͟t͟h͟r͟o͟w͟ ͟r͟e͟s͟p͟o͟n͟s͟e͟;͟
    });

    //IMPORTANT
    //RETURN the promise
    ͟ ͟r͟e͟t͟u͟r͟n͟ ͟s͟e͟a͟r͟c͟h͟_͟r͟e͟s͟p͟o͟n͟s͟e͟;͟

};

当函数缺少return语句时,它返回值undefined

同样重要的是re-throw拒绝处理程序中的错误响应。否则,被拒绝的承诺将转换为已履行的承诺,其价值为undefined