0

我在这里有一个工作 plunkr:plunkr,它定义并使用一个过滤器,将一个项目附加到预先输入的建议列表中。当我尝试将其合并到我的项目中时,它会在过滤器周围引发错误。这是我的代码:

html:

<div class="input-group" ng-controller="TypeaheadCtrl">
            <input type="text" ng-model="search" placeholder="Search for vendors or products" class="form-control"
               ng-bind-html="match.label | typeaheadHighlight:query"
              typeahead="product for product in getProductSuggestions($viewValue) | filter:$viewValue | finalAppend:$viewValue">

脚本:

var app = angular.module('clientApp')
app.controller('TypeaheadCtrl', function ($scope, $http, StateService) {
    $scope.getProductSuggestions = function(val) {
        return $http.get(StateService.getServerAddress() + "search/autocomplete?q=" + val
            ).then(function(response){
            return response.data.products;
        });
    };
  })

app.filter('finalAppend', function($sce){
      return function(array, value){
        array.push(  // error: undefined is not a function!
            $sce.trustAsHtml('Look for <b>' + value + '</b> in other shops')
        ); 
        return array;
      }
})

提前致谢。

编辑:最后我刚刚摆脱了过滤器,当我得到结果时,我将最后一件事附加到承诺本身。

4

1 回答 1

1

问题是该函数getProductSuggestions没有检索数组。那是因为该函数正在发出一个 asinc 请求,而您return在 promise 的函数中有集合then

您需要对代码进行相当多的更改。

在您看来,这样做:

<input type="text" ng-model="search" placeholder="Search for vendors or products" 
  class="form-control" 
  ng-change="updateProductSuggestions(search)" 
  ng-bind-html="match.label | typeaheadHighlight:query"
  typeahead="product for product in productSuggestions | filter:$viewValue | finalAppend:$viewValue">

在你的控制器中这样做:

app.controller('TypeaheadCtrl', function ($scope, $http, StateService, $timeout) {
    $scope.productSuggestions =[];
    $scope.updateProductSuggestions= function(val) {
        return $http.get(StateService.getServerAddress() + "search/autocomplete?q=" + val
            ).then(function(response){
            $timeout(function(){
                  $scope.productSuggestions = response.data.products;
            });
        });
    };
  })

另外,请确保您输入的response.data.products是有效的数组。

最后,您还可以$filter像这样改进:

app.filter('finalAppend', function($sce){
      return function(array, value){
        if(!(array && value))
            return array;
        array.push(
            $sce.trustAsHtml('Look for <b>' + value + '</b> in other shops')
        ); 
        return array;
      }
})
于 2014-11-03T19:36:42.163 回答