【问题标题】:Angularjs search with exclamation as first letterAngularjs以感叹号作为第一个字母进行搜索
【发布时间】:2018-04-04 13:08:54
【问题描述】:

Angularjs:搜索以 ! 开头时搜索过滤器不起作用(感叹号)

如果我的数据类似于 name='Anand!'

客户端过滤器应该与 searchWord='!' 一起使用

如果有人有同样的解决方案,请给我同样的解决方案。

提前致谢!!

我的代码:

<input type="search" class="form-control" ng-model="searchtext" 
placeholder="search here..." />

<div ng-repeat="cust in customers |orderBy:'id' | filter:searchtext">
</div>

$scope.customers = [{
        "id": 1,
        "first_name": "Anand!",
        "last_name": "GK",
        "gender": "Male"           
    }, {
        "id": 2,
        "first_name": "ABC !",
        "last_name": "XYZ",
        "gender": "Female"
    }];

【问题讨论】:

标签: angularjs filter


【解决方案1】:

在上面的示例中,您仅在 first_name 上提供了过滤器,并且该功能对所有人都是通用的,因此我们可以在任何地方使用它

这也可以实现,您只需获取object 中所有字段的值,然后匹配searchText,如下所示:-

你需要做的就是写一个你自己的custom filter

angular.module('app', []).controller('ctrl', function($scope) {
$scope.customers = [{
    "id": 1,
    "first_name": "Anand!",
    "last_name": "GK",
    "gender": "Male"           
}, {
    "id": 2,
    "first_name": "ABC !",
    "last_name": "XYZ",
    "gender": "Female"
}];
}).filter('searchFilter', function() { /* this the Custom Filter, you can code it to include other fields in search too */
  return function(input, searchText) {
    if (!searchText)
      return input;
    var matchedRecord = [];
    var matchFound = false;
    for (var i = 0; i < input.length; i++){
       for (var key in input[i]) {
          if(input[i][key] != undefined && input[i][key].toString().toLowerCase().indexOf(searchText.toLowerCase()) != -1) {
             matchFound = true;
          }
       }
       if(matchFound)
          matchedRecord.push(input[i]);
       matchFound = false;
    }
    return matchedRecord;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <input type='text' ng-model='searchText' />
  <ul>
    <li ng-repeat='customer in customers | searchFilter: searchText'>{{customer | json}}</li>
  </ul>
</div>

【讨论】:

  • 感谢您的快速回复,但我们希望过滤整个数据而不是特定字段。在上面的示例中,您仅在 first_name 上提供了过滤器,并且该功能对所有人都是通用的,因此我们可以在任何地方使用它。
  • @AnandGaikwad 编辑了答案,现在是通用的filter
  • 只需要进行一项更改:在转换为字符串之前添加检查字段值是否为空或未定义。
猜你喜欢
  • 2017-04-20
  • 2018-01-21
  • 2018-05-15
  • 1970-01-01
  • 2019-11-11
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
相关资源
最近更新 更多