我有以下 html 代码:
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test">
{{ x }}
</li>
</ul>
对应的JS是:
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jabi',
'Cabi',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
问题是当我键入“bi”时,过滤器会返回所有包含“bi”的名称,但是我希望过滤器应该只返回以“bi”开头的名称(或者 watever 写在输入文本框中)
最佳答案
由于您只需要匹配的大小写/字母,因此您必须按如下方式创建自定义过滤器,
演示
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jabi',
'Cabi',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
$scope.onlyMatch = function (input, output) {
var Str = (input + "").toLowerCase();
return Str.indexOf(output.toLowerCase()) === 0;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test:onlyMatch">
{{ x }}
</li>
</ul>
</body>
关于javascript - 从给定文本开始的 Angularjs 过滤器搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48536199/