我在Angular 1.4.8中。我正在使用基本搜索過濾器來查找用戶。搜索工作,但正在搜索整個數據集。例如,在下面搜索「Mar」可以找到三個結果,因爲一個姓氏包含Mar。我想僅以名字搜索。最終目標是找到找到的記錄數:結果{{count}}。所以尋找「聖」應該找到一個結果,第一個名字史蒂夫(不是斯坦福)。AngularJS按特定項目過濾
這裏有一個小提琴: 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;
});
}]);
謝謝@ luis-machillanda完美地工作! – mediaguru