【问题标题】:filter issues with getJSON return call in Typeahead (AngularJS directive)过滤 Typeahead 中 getJSON 返回调用的问题(AngularJS 指令)
【发布时间】:2015-01-29 15:55:26
【问题描述】:

我在使用 Typeahead 中的过滤器功能时遇到问题。当我使用静态列表时(参见下面的$scope.statesWithFlags),过滤器会按预期工作,即它只显示与输入查询匹配的结果。

$scope.statesWithFlags = [{
    'name': 'Alabama',
    'flag': '5/5c/Flag_of_Alabama.svg/45px-Flag_of_Alabama.svg.png'
  }, {
    'name': 'Alaska',
    'flag': 'e/e6/Flag_of_Alaska.svg/43px-Flag_of_Alaska.svg.png'
  }, {
    'name': 'Arizona',
    'flag': '9/9d/Flag_of_Arizona.svg/45px-Flag_of_Arizona.svg.png'
  }, {
    'name': 'Connecticut',
    'flag': '9/96/Flag_of_Connecticut.svg/39px-Flag_of_Connecticut.svg.png'
  }];

但是,当我使用一个简单的getJSON 调用时,它输出完全相同的$scope.statesWithFlags 结果,然后所有可能的结果不断显示,过滤器功能| filter:{name:$viewValue} 似乎不起作用。 limitTo:6 也是如此。我必须明确返回响应吗?如果是这样,怎么做?

$scope.statesWithFlags = $.getJSON('/typeahead');

这是我正在使用的输入元素:

<input type="text" ng-model="customSelected" typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-template-url="customTemplate.html" class="form-control">

【问题讨论】:

    标签: jquery ajax angularjs typeahead.js


    【解决方案1】:

    您需要设置一个回调函数来获取响应然后分配。因为$.getJSON('/typeahead') 是一个请求对象,而不是来自您服务器的响应。

    $.getJSON('/typeahead',function(response){
        //parse your response and assign it
        $scope.statesWithFlags = response;
    });
    

    P.D:为什么要使用 jQuery ajax 调用,什么时候可以使用 $http angular 模块。

    【讨论】:

    • 谢谢!这就像一个魅力。仍然习惯了角度,所以会检查 $http
    • @koend 是的,尽量避免使用 jquery。
    【解决方案2】:

    如果上面的答案没有帮助人们在 angularjs 中使用 $http 调用并且其 api 响应太大,在我的情况下是 70,000 行: 我最近在我的 angularjs 应用程序中遇到了同样的问题。我在我的 HTML 中使用了这个: &lt;input class="form-control" style="text-overflow: ellipsis" id="diagnosis-list" type="text" ng-model="diagnosis" typeahead="searchDiagnosis as searchDiagnosis.type_code + ' &amp;nbsp : ' + searchDiagnosis.type_code_value for searchDiagnosis in getMatchingDiagnosisList($viewValue)" typeahead-on-select="selectDiagnosis($item)">

    getMatchingDiagnosisList() 在控制器中编写如下:

    $scope.getMatchingDiagnosisList = function($viewValue){
          console.log("$viewValue",$viewValue);
          if($viewValue.length == 2 || $viewValue.length > 2){
            console.log("$viewValue.length",$viewValue.length);
                xService.getDiagnosticList($viewValue).then(function(response){
               $scope.searchDiagnosis = {};
              if(response.data.typeCode){
              $scope.searchDiagnosis = response.data;
            }
            else{
               $scope.searchDiagnosis = {'typeCode':[]};
            }
    
            }).catch(function(){
               $scope.searchDiagnosis = {'typeCode':[]};
            });  
            return $scope.searchDiagnosis.typeCode;
        }
        };
    

    正在调用 angularjs 服务,其中包含以下 API 调用:

    getDiagnosticList: function(value){
            var url = URL.matchingDiagnosticList.replace("SEARCH_STRING",value)
             return $http.get(url, {
              headers: headerService.getHeader()
            }).success(function(response) {
              return response;
            });
          }
    

    由于调用了rest API,此代码无法正常工作,因此经过大量调试后,我将控制器功能编辑为:

        $scope.getMatchingDiagnosisList = function($viewValue){
              $scope.isLoading = true;
    //Whatever you return below will be taken as a parameter in getMatchesAsync() of the directive, so modify the directive accordingly
                return patientService.getDiagnosticList($viewValue);    
              };          
        };
    

    在我的例子中,我修改了路径 bower_components\angular-bootstrap\ui-bootstrap-tpls.js 或 bower_components\angular-bootstrap\ui-bootstrap.js 中的指令 getmatchesasync(),如下所示:

    var getMatchesAsync = function(inputValue) {
          var locals = {$viewValue: inputValue};
          isLoadingSetter(originalScope, true);
          isNoResultsSetter(originalScope, false);
          $q.when(parserResult.source(originalScope, locals)).then(function(matchesFull) {
            //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
            var matches = matchesFull.data.typeCode;
            var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
            if (onCurrentRequest && hasFocus) {
              if (matches && matches.length > 0) {
    
                scope.activeIdx = focusFirst ? 0 : -1;
                isNoResultsSetter(originalScope, false);
                scope.matches.length = 0;
    
                //transform labels
                for (var i = 0; i < matches.length; i++) {
                  locals[parserResult.itemName] = matches[i];
                  scope.matches.push({
                    id: getMatchId(i),
                    label: parserResult.viewMapper(scope, locals),
                    model: matches[i]
                  });
                }
    
                scope.query = inputValue;
                //position pop-up with matches - we need to re-calculate its position each time we are opening a window
                //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
                //due to other elements being rendered
                recalculatePosition();
    
                element.attr('aria-expanded', true);
    
                //Select the single remaining option if user input matches
                if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) {
                  scope.select(0);
                }
              } else {
                resetMatches();
                isNoResultsSetter(originalScope, true);
              }
            }
            if (onCurrentRequest) {
              isLoadingSetter(originalScope, false);
            }
          }, function() {
            resetMatches();
            isLoadingSetter(originalScope, false);
            isNoResultsSetter(originalScope, true);
          });
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多