我在Angular 1.4.8。我正在使用基本搜索过滤器来查找用户。搜索有效,但正在搜索整个数据集。例如,在下面搜索“Mar”会找到三个结果,因为一个姓氏包含Mar.我想只搜索名字。最终目标是找到找到的记录数:结果{{count}}。所以搜索“St”应该找到一个结果,名字史蒂夫(不是斯坦福)。
这是一个小提琴: http://jsfiddle.net/mediaguru/z5shgzxw/1/
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<input type="text" ng-model="search">
<table>
<tbody>
<tr ng-repeat="item in items">
<td>ID: {{item.id}}</td>
<td>Name: {{item.firstname}}</td>
<td>Gender: {{item.lastname}}</td>
</tr>
</tbody>
</table>
Result {{count}}
</div>
</div>
JS
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$filter', function($scope, $filter) {
$scope.items = [{
id: 1,
firstname: 'John',
lastname: 'Jones'
}, {
id: 2,
firstname: 'Steve',
lastname: 'Jones'
}, {
id: 3,
firstname: 'Joey',
lastname: 'Maritza'
}, {
id: 4,
firstname: 'Mary',
lastname: 'Linqust'
}, {
id: 5,
firstname: 'Marylin',
lastname: 'Stanford'
}];
$scope.items2 = $scope.items;
$scope.$watch('search', function(val) {
$scope.items = $filter('filter')($scope.items2, val);
$scope.count = $scope.items.length;
});
}]);
答案 0 :(得分:4)
你必须这样做:
$scope.items = $filter('filter')($scope.items2, {firstname:val});
就是这样。
答案 1 :(得分:0)
您必须写($scope.items2, {firstname:val});
您可以使用以下代码解决问题。
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$filter', function($scope, $filter) {
$scope.items = [{
id: 1,
firstname: 'John',
lastname: 'Jones'
}, {
id: 2,
firstname: 'Steve',
lastname: 'Jones'
}, {
id: 3,
firstname: 'Joey',
lastname: 'Maritza'
}, {
id: 4,
firstname: 'Mary',
lastname: 'Linqust'
}, {
id: 5,
firstname: 'Marylin',
lastname: 'Stanford'
}];
$scope.items2 = $scope.items;
$scope.$watch('search', function(val) {
$scope.items = $filter('filter')($scope.items2, {firstname:val});
$scope.count = $scope.items.length;
});
}]);