如何仅按名称过滤列表 - AngularJS

时间:2018-05-29 12:31:20

标签: angularjs

所以我需要按名称实现搜索过滤器。我对angularjs并不擅长,所以我可以使用一些帮助。这就是我现在所做的,但它需要一些调整:

<input type="text" ng-model="searchText" placeholder="Search for a pupil..." />

<tr ng-repeat="student in studentData | filter : searchText">

只是这个过滤器。但是在studentData中,我应该只搜索studentData.FullName。最简单的方法是什么?

3 个答案:

答案 0 :(得分:1)

检查以下代码..

<input type="text" ng-model="searchText" placeholder="Search for a pupil..." />

<tr ng-repeat="student in studentData | filter :{name:searchText}:true">

答案 1 :(得分:1)

我相信您可以像这样指定要过滤的属性:

<tr ng-repeat="student in studentData | filter : {fullName: searchText}">

但是,请记住,这将是精确的文本匹配,包括套管“Joe”不等于“joe”。

上述方法可行,但IMO不是最佳解决方案。以下是我的建议

将HTML更改为指向新的数据数组:

<input type="text" ng-model="searchText" placeholder="Search for a pupil..." />
<tr ng-repeat="student in filteredStudentData">

在你的控制器中:

$scope.searchText = ''; //start as an empty string
$scope.studentData = [ ... ]; //your real data goes in here
$scope.filteredStudentData = []; // start as an empty array

//Watch the `searchText` property for changes
$scope.$watch('searchText ', function(newValue, oldValue){
  //remove whitespace, and make it all lowercase - note the `.trim()` only works on IE 9+
  var normalizedSearchText = (newValue || '').toLowerCase().trim();

  //Now only include the relevant results in the `filteredStudentData` array
  //note that the `.filter()` method is only available on IE9+
  $scope.filteredStudentData = $scope.studentData.filter(function (student) {
    return 
       normalizedSearchText === student.fullName.toLowerCase().trim() ||
       normalizedSearchText === student.someOtherProperty.toLowerCase().trim() ||
       normalizedSearchText === student.anotherExampleProperty.toLowerCase().trim();
  });
});

答案 2 :(得分:1)

试试这个

<input type="text" ng-model="searchText" placeholder="Search for a pupil..." />

<tr ng-repeat="student in studentData | filter:{student.Fullname:searchText}">