如何使用$ resource填充Angular UI Bootstrap typeahead

wob*_*col 7 asynchronous twitter-bootstrap angularjs

我试图让Angular UI bootstraps typeahead使用我设置的REST资源.但我不确定如何使用它的异步特性.

目前我已经调整了Angular UI Bootstrap给出的示例.

所以我的html看起来像这样,调用getLibs()来获取typeahead下拉列表.

<div class='container-fluid' ng-controller="TypeaheadCtrl">
    <pre>Model: {{selected| json}}</pre>
    <input type="text"  typeahead="lib.name for lib in getLibs($viewValue)" active='active' ng-model="selected" typeahead-min-length='3' >
</div>
Run Code Online (Sandbox Code Playgroud)

我的资源看起来像这样:

angular.module('LibraryLookupService', ['ngResource']).factory('Library', 
    function($resource){
        return $resource(   "../../api/seq/library/?name__icontains=:searchStr" , {} , 
        {   'get':    {method:'GET'},
            'query':  {method:'GET', params: {} ,  isArray:false },
        }
    )
}
Run Code Online (Sandbox Code Playgroud)

);

我的控制器看起来像这样(我猜它在这里我做的事情不正确):

function TypeaheadCtrl($scope , Library){

    $scope.selected = undefined;
    $scope.active = undefined ;

    $scope.libs = [{name:'initial'} , {name:"values"}];

    $scope.getLibs = function(viewValue){
        console.log("value:", viewValue);
        if (viewValue.length > 3 ) { 
            var return_vals =  Library.query({searchStr:viewValue},  function() {
                $scope.libs = return_vals.objects ; 
                console.log("here", $scope.libs) ; 
                }) ;
            }
        return $scope.libs
    }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,从www.Lines()函数的返回值填充了typeahead菜单.当调用getLibs()时,它正在查询REST接口,但最初返回一个空值.这是由提供给Library.query()方法的函数填充的,这是在从REST请求返回数据之后完成的.

这基本上意味着菜单正在比我想要的更晚一次按键更新.我输入'3456',它会在REST接口中填入'345'查询结果.

当从Library.query()函数返回响应时,如何更新菜单?我正确地谈到这个吗?

Joa*_*ido 7

我这样解决了:

我的工厂:

angular.module('frontendApp')
  .factory('PersonService', function($resource) {
    // Service logic
    // ...

    return $resource(APP_CONFIG.prefixURLRest + '/person', {
      //id: '@id'
    }, {
      search: {
        method: 'POST',
        isArray: true
      }
    });

  });
Run Code Online (Sandbox Code Playgroud)

我的控制器

...
$scope.searchTypeAhead = function(name) {
  var person = {
    'name': name
  };

  return PersonService.search(person)
    .$promise.then(function(response) {
      return response;
    });
};
Run Code Online (Sandbox Code Playgroud)

  • 实际上你可以在没有then()方法的情况下返回$ promise,因为它是多余的. (7认同)

pko*_*rce 6

来自http://angular-ui.github.io/bootstrap/的typeahead指令继承promise API($q)以处理异步建议.麻烦的$resource是用于缺乏对promises的支持(它最近才在unstable分支中添加).所以你有两个解决方案:

1)继电器$http使用promises(对于大多数自动完成的情况,IMO $ http应该足够了).2)切换到AngularJS的最新不稳定版本并使用promises.

$ resource的目的是使用完整的HTTP谓词来定位RESTful端点.如果您只想查询数据,最好还是使用$ http来实现此目的.

关于typeahead还有一个类似的问题,答案涵盖了它的用法$http:如何通过$ http为服务器端优化将angular-ui的typeahead与服务器联系起来?