【问题标题】:AngularJS UI Bootstrap typeahead with ajax using CoffeescriptAngularJS UI Bootstrap typeahead with ajax using Coffeescript
【发布时间】:2013-09-30 05:05:28
【问题描述】:

我的问题与this post 'Using typeahead and ajax in a AngularJS app'非常相似

咖啡脚本:

  $scope.tradingPartners = (searchOn) ->
    console.log("Searching on #{searchOn}")
    $.getJSON("../tp/tpLookupAdmin", {term: searchOn, max: 20}, (response)->
        response)

生成 Javascript:

$scope.tradingPartners = function(searchOn) {
      console.log("Searching on " + searchOn);
      return $.getJSON("../tp/tpLookupAdmin", {
        term: searchOn,
        max: 20
      }, function(response) {
        return response;
      });
    };

使用它:

<input type="text" ng-model="testScript.sender" typeahead="sender as sender.label for sender in tradingPartners($viewValue)" 

那怎么了? ...

getJSON 调用很好,结果看起来不错,但 typeahead 没有做任何事情。如果我把硬编码的值作为函数的返回值,它就可以正常工作。

现在我知道 getJSON 不仅仅是返回一个对象数组,而是在做

$.getJSON("../tp/tpLookupAdmin", {term: searchOn, max: 20}, (response)->
        response).responseJSON

给出未定义的。

有效的硬编码 json 示例:

[{"id":"1","label":"test1"},{"id":"2","label":"test2"}]

我在这里遗漏了一些简单的东西......

编辑(来自 kju 的回答):

现在生成的 JS 是

$scope.tradingPartners = function(searchOn) {
  return $http.post("../tp/tpLookupAdmin?term=" + searchOn).then(function(response) {
    return limitToFilter(response, 15);
  });
};

但它仍然无法正常工作......

【问题讨论】:

    标签: twitter-bootstrap angularjs coffeescript angular-ui-bootstrap


    【解决方案1】:

    你引用的问题已经有了你需要的所有答案,所以你的问题真的不是一个好问题。

    查找函数必须返回一个数组或一个(AngularJS 风格的)promise。您返回的是 $.getJSON 的返回值,两者都不是。代码中的回调函数将返回一个数组,但无处可去。它不会最终出现在 Angular 中。这无济于事,因为您在这里发出异步 HTTP 请求。当请求返回时,你的查找函数早就返回了。因此,您需要返回一个承诺。 AngularJS 知道如何处理这个承诺并处理延迟的数据。

    正如我所说,另一个问题及其接受的答案已经包含了所有内容。摆脱 $.getJSOn 并使用 Angular 中的 $http 服务,如图所示。

    【讨论】:

    • 感谢您的回答,我已经进行了更改,我认为 JS 看起来不错,但预输入仍然不起作用...会继续尝试。
    【解决方案2】:

    最后我还是选择了 select2。无论如何,我认为在我的情况下这是一种更清晰、更一致的方法。

    <input ui-select2="tpSearch" ng-model="testScript.sender" class="input-xlarge"/>
    

    咖啡脚本:

    $scope.tpSearch =
        placeholder: "Type to search..."
        minimumInputLength: 2
        ajax:
          url: "../tp/tpLookupPaged"
          quietMillis: 100
          data: (term, page) ->
            term: term # query params 
            page: page
            max: 10
          results: (data, page) ->  
             more = (page * 10) < data.total
             results: data.results, more: more
    

    实现无限滚动是轻而易举的事。

    确保您的 JSON 返回一个包含 id 和文本的数组,否则您必须为 select2 编写一个自定义格式化函数(无论如何都很简单)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多