Savan S
Savan S

Reputation: 417

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

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'

Upvotes: 4

Views: 628

Answers (2)

Slava Utesinov
Slava Utesinov

Reputation: 13488

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>

Upvotes: 2

jose
jose

Reputation: 1054

Try this way

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

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

Upvotes: 0

Related Questions