Angularjs: Search filter not working when name starting with ! (exclamation mark)

女生的网名这么多〃 提交于 2019-12-23 12:26:52

问题


I have list of states and I have added search filter on name of states. I have array like this:

stateList : [{name: 'abc', area:500},{name: '!def', area:500}]

I have <li> with ng-repeat="state in stateList | filter:{name:searchText}"

Search text box with ng-model="searchText"

Search is working in normal scenario but when I search !(exclamation mark). It is not giving any result. It should give state with name '!def'


回答1:


The problem is that ! token is recognized by AngularJS as "negative predicate". Nevertheless you can create your custom myFilter like this:

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.stateList = [{
    name: 'abc',
    area: 500
  }, {
    name: '!def',
    area: 500
  }]
}).filter('myFilter', function() {
  return function(input, filter) {
    if (!filter.name)
      return input;
    return input.filter(function(x) {
      return x.name.indexOf(filter.name) != -1;
    });
  }
})
<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='state in stateList | myFilter : {name:searchText}'>{{state | json}}</li>
  </ul>
</div>



回答2:


Try this way

<input type="text" ng-model="state.name"/>

ng-repeat="state in stateList | filter:state"


来源:https://stackoverflow.com/questions/47587719/angularjs-search-filter-not-working-when-name-starting-with-exclamation-mark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!