我正在尝试 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/