在AngularJS应用程序中使用typeahead和ajax

时间:2013-08-02 20:38:28

标签: twitter-bootstrap angularjs

我在使用Bootstrap-UI的带有动态数据的预先控制(从ajax调用获取的数据)时遇到问题。

我的服务中的响应看起来有点像[{id:1, text:'somebrand'},{id:2, text:'something'}]

HTML看起来像这样:

<input type="text" ng-model="result" min-length="2" typeahead="brand.id as brand.text for brand in brands($viewValue)" style="display:block">

在我的控制器中,我检索这样的内容:

$scope.brands = function(brandName){
        $http.post('/brands/getbrandsviewmodel', { query : brandName}).then(function(response){
            return limitToFilter(response.data, 15);
        });
    };

我遇到的问题是Bootstrap-UI中的错误,如下所示:

 Cannot read property 'length' of undefined
at http://localhost:3000/assets/ui-bootstrap-tpls-0.4.0.js?body=1:2749:24

当我调试Bootstrap-UI代码时,我看到此处发生错误,并且匹配未定义:

//it might happen that several async queries were in progress if a user were typing fast
          //but we are interested only in responses that correspond to the current view value
          if (inputValue === modelCtrl.$viewValue) {
            if (matches.length > 0) {....

我最初的反应是,Bootstrap-UI的typeahead不知道何时检索数据,但我不知道为什么,因为我使用的是promises?

1 个答案:

答案 0 :(得分:13)

您需要实际brands函数返回承诺。试试这个:

$scope.brands = function(brandName){
       return $http.post('/brands/getbrandsviewmodel', { query : brandName})
                     .then(function(response){
                        return limitToFilter(response.data, 15);
                      });
    };