【问题标题】:Angularjs: Search filter not working when name starting with ! (exclamation mark)Angularjs:名称以 ! 开头时,搜索过滤器不起作用(感叹号)
【发布时间】:2018-05-15 05:22:55
【问题描述】:

我有州列表,并在州名上添加了搜索过滤器。 我有这样的数组:

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

我有<li>ng-repeat="state in stateList | filter:{name:searchText}"

使用ng-model="searchText"搜索文本框

搜索在正常情况下工作,但当我搜索时!(感叹号)。它没有给出任何结果。它应该给出名称为'!def'的状态

【问题讨论】:

标签: javascript angularjs search filter


【解决方案1】:

试试这个方法

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

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

【讨论】:

  • 我只想在 state 的 name 属性上添加过滤器。所以我必须定义filter:{name:searchText}
  • 对不起。但没有得到你的答案。文本框用于搜索。正确的?你为什么在搜索文本框中写state.name
【解决方案2】:

问题在于! 标记被AngularJS 识别为“否定谓词”。不过,您可以像这样创建您的自定义 myFilter

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2015-10-02
    • 2015-03-12
    • 2014-08-06
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2018-08-23
    相关资源
    最近更新 更多