javascript - 为什么这个 Angular-ui TypeAhead 代码返回所有项目而不是过滤的项目?

标签 javascript angularjs angular-ui typeahead angular-ui-typeahead

我正在尝试 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"  
}
]

最佳答案

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

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;
      });
  };
}

关于javascript - 为什么这个 Angular-ui TypeAhead 代码返回所有项目而不是过滤的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23780792/

相关文章:

javascript - 单击其中的单选选项时更改 div 类

javascript - 创建计算输入框的动态表单

javascript - Angular formly - 在 templateOptions 变量上设置观察者

javascript - Angular JS 1 - 添加框架时出错

javascript - Angular ui grid如何在网格中显示html

javascript - Firebase 云消息传递无法检索实例 ID

forms - angular - 在指令中的表单元素之间动态更改验证要求

关于隔离范围属性的 AngularJS 文档

twitter-bootstrap - AngularJS 和 Bootstrap 拆分按钮下拉菜单

javascript - 为什么我的 angular-bootstrap 选项卡不呈现?