使用过滤器进行搜索但忽略标点符号

时间:2015-07-03 06:55:44

标签: angularjs ionic-framework ionic angularjs-filter

我为下面的离子项目写了一个搜索过滤器。它工作正常,但它不会忽略标点符号。

因此,如果我正在搜索带有逗号的项目而且我想念逗号的项目,我将无法找到它。有没有办法告诉过滤器忽略逗号,甚至可能还有其他标点符号?

请参阅以下示例的几个片段:

<input class="search-bar" type="search" placeholder="Search" ng-model="data.searchQuery">
<ion-list>
  <ion-item  collection-repeat="hymn in hymns | filter: data.searchQuery">
    <h2><b>{{hymn.number}}. </b>{{hymn.title}}</h2>
  </ion-item>
</ion-list>

的Javascript

var hymns = [
{
    "body": "I've written a body, it has punctuation too;\n",
    "number": 1,
    "title": "This Title, has a comma! and puctuations"
}, ...

2 个答案:

答案 0 :(得分:1)

  1. 您可以调用函数来过滤项目:

    <ion-item collection-repeat="hymn in hymns | filter: myCustomFilter">
        <h2><b>{{hymn.number}}. </b>{{hymn.title}}</h2>
        <p>{{hymn.body}}
    </ion-item>
    

    然后在控制器中定义它:

    $scope.myCustomFilter = function(hymn) {
        var searchTerm = $scope.data.searchQuery || '';
        searchTerm = searchTerm.replace(/[^\w\s]|_/g, "").toLowerCase()
    
        var hymnTitle = hymn.title.replace(/[^\w\s]|_/g, "").toLowerCase();
        var hymnBody = hymn.body.replace(/[^\w\s]|_/g, "").toLowerCase();    
    
        return hymnTitle.indexOf(searchTerm) > -1|| hymnBody.indexOf(searchTerm) > -1;
    }
    

    Codepen example using function

  2. 您还可以创建自定义角度滤镜:

    <ion-item collection-repeat="hymn in hymns | filterPunctuation: data.searchQuery">
        <h2><b>{{hymn.number}}. </b>{{hymn.title}}</h2>
        <p>{{hymn.body}}
    </ion-item>
    

    然后像这样定义过滤器:

    .filter('filterPunctuation', function() {
      return function(items, searchTerm) {
        if (!searchTerm || '' === searchTerm) {
          return items;
        }
    
        searchTerm = searchTerm.replace(/[^\w\s]|_/g, "").toLowerCase();
    
        return items.filter(function(element, index, array) {
          var title = element.title.replace(/[^\w\s]|_/g, "").toLowerCase();
          var body = element.body.replace(/[^\w\s]|_/g, "").toLowerCase();
          return title.indexOf(searchTerm) > -1 || body.indexOf(searchTerm) > -1;
        });
      }
    })
    

    Codepen example using filter

  3. 我使用正则表达式从搜索词和赞美诗属性中过滤掉所有标点符号的两种方式,然后我将它们都转换为小写,这样用户就不必键入它完全如此。有很多不同的方法可以做到这一点。希望这有帮助!

答案 1 :(得分:0)

你可以这样做

<input class="search-bar" type="search" placeholder="Search" ng-model="data.$">
<ion-list>
  <ion-item  collection-repeat="hymn in hymns | filter: data">
    <h2><b>{{hymn.number}}. </b>{{hymn.title}}</h2>
  </ion-item>
</ion-list>

plunker:http://plnkr.co/edit/I9XEk7ebBeWbzQtwdMPv?p=preview

我希望这会对你有所帮助