Bootstrap ui typeahead async not working

时间:2015-09-22 17:30:36

标签: angularjs angular-ui-bootstrap angular-promise

我正在使用bootstrap ui typeahead。因此,当用户输入我想要异步加载数据时。所以我创建了一个工厂,它有一个http req来获取数据。

angular.module('customers').controller('CustomersController', ['$scope', function($scope){
        $scope.searchUser = function(val) {
            searchUser.getUsers(val, $scope.searchField, $scope.searchPattern, $scope.displayCount).then(function(response){
                    // console.log(response.data
                    return response.data
                });
            }
    }]).factory('searchUser', ['$http', function($http) {
            return {
                getUsers: function(val, callback){
                    return $http({
                        url: '/search/user/' + val,
                        method: 'GET'
                    })
                }
            }
        }]);

HTML:

<input type="text" ng-model="selectedUser" placeholder="Search User" typeahead="user.firstname for user in searchUser($viewValue) | filter:{firstname:$viewValue}" typeahead-on-select="onSearchItemSelect($item, $model, $label)" class="form-control">

但我继续收到以下错误

  

TypeError:无法读取未定义的属性“长度”   在ui-bootstrap-tpls.js:3186
      在m.promise.then.u(angular.js:11319)
      在m.promise.then.u(angular.js:11319)
      在angular.js:11405
      at h.a. $ get.h. $ eval(angular.js:12412)
      at h.a. $ get.h. $ digest(angular.js:12224)
      at h.a. $ get.h. $ apply(angular.js:12516)
      在HTMLInputElement.l(angular.js:16632)
      在HTMLInputElement.jQuery.event.dispatch(jquery.js:4409)
      在HTMLInputElement.jQuery.event.add.elemData.handle(jquery.js:4095)

我几乎尝试了stackoverflow上接受的所有答案。但是我得到了同样的错误。

修改 仅供参考:我尝试更改功能名称(因为功能和工厂名称相同),但没有帮助。如果我在控制台中记录了函数中的response.data,我可以看到返回的输出,但它不会返回到前面的类型。

实际上,以下代码无需创建工厂即可运行。但问题是,当我转到加载相同控制器的不同页面时,此承诺会自动继续获取导致页面冻结的请求。

$scope.searchUser = function(val) {
    return $http.get('/search/user/' + val)
    .then(function(response){
        return response.data
    })
}

1 个答案:

答案 0 :(得分:0)

你不应该以这种方式使用limitTo过滤器,首先应该向控制器注入$ filter依赖项,然后使用limitTo过滤器

  

应该像

     

$filter('limitTo')(input, limit, begin)

<强>代码

.controller('CustomersController', ['$scope', '$filter', function($scope, $filter) {
    $scope.searchUser = function(val) {
      return $http.get('/search/user/' + val)
        .then(function(response) {
          return $filter('limitTo')(response.data, 10);
        });
    }
}]).
相关问题