2017-08-02 72 views
0

我在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; 
    }); 


    }]); 

回答

4

必須這樣做:

$scope.items = $filter('filter')($scope.items2, {firstname:val}); 

這一切。

+0

謝謝@ luis-machillanda完美地工作! – mediaguru

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; 
}); 
}]);