我是Angular的新手,我正在寻找一种更优雅的方式来解决这个问题。
Code bellow工作得很好,但我不确定这是否是完成它的正确方法。
HTML
<div ng-app="ngFilterApp" ng-controller="namesCtrl">
<p>Filtering input:</p>
<p><input type="text" ng-model="search" /></p>
<ul>
<li ng-repeat="x in names | myFilter">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
JS
var searchVal;
angular.module('CustomFilterModule', [])
.filter('myFilter', function() {
return function( input ) {
searchVal = searchVal || '';
var s = searchVal.toLowerCase();
var arr = [];
for (var i = 0; i < input.length; i++) {
if(input[i].name.toLowerCase().indexOf(s) === 0 || input[i].country.toLowerCase().indexOf(s) === 0) arr.push(input[i]);
}
return arr;
};
});
angular.module('ngFilterApp', ['CustomFilterModule'])
.controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Moscow',country:'Russia'},
{name:'Kiev',country:'Ukraine'},
{name:'Yerevan',country:'Armenia'},
{name:'Washington',country:'USA'},
{name:'Madrid',country:'Spain'},
{name:'Tbilisi',country:'Georgia'}
];
$scope.$watch('search', function() { searchVal = $scope.search; }, true);
});
答案 0 :(得分:0)
您可以将查询字符串作为参数传递给过滤器,请参阅修改后的JSBIN: