0

我正在尝试 angular-ui typeahead 指令。期望的结果是输入框应该只显示基于输入内容的过滤项目。我的代码显示所有项目。

我在http://plnkr.co/edit/8uecuPiVqmEy6gFQYeXC为代码创建了一个 plunker

它有什么问题?非常感谢你。

万一你不能访问plunker,相关的html代码是这样的;

<div class='container-fluid' ng-controller="TypeaheadCtrl">
    <h4>Testing angular-ui Typeahead</h4>
    <!-- <pre>Model: {{asyncSelected | json}}</pre> -->
    <input type="text" ng-model="typeahead" typeahead="names for names in getName($viewValue) " class="form-control">    
</div>

相关的JS代码是这样的;

function TypeaheadCtrl($scope, $http) 
{
  // Any function returning a promise object can be used to load values asynchronously  
  $scope.getName = function(val) 
  {
    return $http.get('test.json') 
    .then(function(res)
    {
        var names = [];
        angular.forEach(res.data, function(item)
        {
            names.push(item.name);
        });
        return names;
    });
  };
}

http get 的 json 文件如下所示;

[
{
    "name": "Tom"   
},
{
    "name": "Tom2"  
}
]
4

1 回答 1

1

因为你总是返回未过滤的数组,最有可能在服务器端完成,但如果数组是静态的,你可以这样做:

http://plnkr.co/edit/kxOlmnjGA7wX7zhS67aK?p=preview

angular.module('plunker', ['ui.bootstrap']);

function TypeaheadCtrl($scope, $http) {
  // Any function returning a promise object can be used to load values asynchronously  
  $scope.getName = function(val) {
    return $http.get('test.json')
      .then(function(res) {
        var names = [];
        angular.forEach(res.data, function(item) {
          if (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1) {
            names.push(item.name);
          } else {
            console.log(item);
          }
        });
        return names;
      });
  };
}
于 2014-05-21T10:53:52.983 回答