我有以下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)
答案 0 :(得分:2)
由于您只需要匹配的大小写/字母,您必须按如下方式创建自定义过滤器,
<强>样本强>
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;
}
});
&#13;
<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>
&#13;