使用单个文本框向多个字段添加严格搜索

Adding strict search to multiple fields with a single textbox

本文关键字:添加 字段 搜索 单个 文本      更新时间:2023-09-26

有一个基本的角度应用程序

HTML

  <input type="text" ng-model="txt.name" />
  <ul>
    <li ng-repeat="d in data | filter: txt:strict">
      <span>{{d.name}}</span>
      <br />
      <span>{{d.description}}</span>
      <br />
      <span>{{d.loremipsum}}</span>
      <br />
    </li>
  </ul>

JS:

var app = angular.module('app', []);
app.controller("mc", function($scope){
$scope.data = [{
  'name': 'asd',
  'description': 'jiocioasdiasidjpoasdko',
  'loremipsum': 'loremipsum'
}, {
  'name': 'qwe',
  'description': 'poqwpeqwpe',
  'loremipsum': 'loremipsum'
}, {
  'name': 'czxc',
  'description': 'asdasdasd',
  'loremipsum': 'loremipsum'
}]
});

我希望能够通过namedescription进行搜索,但不能通过loremipsum 进行搜索

我该怎么做?

JS BIN 示例

您可以创建自定义过滤器,请参阅下面的演示

var app = angular.module('app', []);
app.controller("mc", function($scope) {
  $scope.data = [{
    'name': 'asd',
    'description': 'jiocioasdiasidjpoasdko',
    'loremipsum': 'loremipsum'
  }, {
    'name': 'qwe',
    'description': 'poqwpeqwpe',
    'loremipsum': 'loremipsum'
  }, {
    'name': 'czxc',
    'description': 'asdasdasd',
    'loremipsum': 'loremipsum'
  }];
});
app.filter('customFilter', function() {
  return function(items, string) {
    var filtered = [];
    var stringMatch = new RegExp(string, 'i');
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (stringMatch.test(item.name) || stringMatch.test(item.description)) {
        filtered.push(item);
      }
    }
    return filtered;
  };
});
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="mc">
  <input type="text" ng-model="txt.name" />
  <ul>
    <li ng-repeat="d in data | customFilter: txt.name">
      <span>{{d.name}}</span>
      <br />
      <span>{{d.description}}</span>
      <br />
      <span>{{d.loremipsum}}</span>
      <br />
    </li>
  </ul>
</body>
</html>

下面是一个使用自定义函数的示例:自定义功能解决方案

您可能希望在自定义函数中使用match而不是===。