javascript 当输入字段为空时,AngularJS 过滤器比较器在显示 ng-repeat 列表时为真

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21199759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:20:49  来源:igfitidea点击:

AngularJS filter comparator true while displaying ng-repeat list when input field is empty

javascriptangularjs

提问by ZvKa

I'm going off by this example fiddle where it demonstrates the use of comparator parameter to filter exact matches....:

我将通过这个示例小提琴开始,它演示了使用比较器参数来过滤精确匹配....:

http://jsfiddle.net/api/post/library/pure/

http://jsfiddle.net/api/post/library/pure/

priority is a number from 1-100, but I have it input as text and filtered as string so any data that includes a substring will also pass through the ng-repeat...like when I type 1 it will also display 11, 111, 132 etc...which is how I came across the :true comparator.

优先级是 1-100 之间的一个数字,但我将它作为文本输入并作为字符串过滤,因此任何包含子字符串的数据也将通过 ng-repeat...就像当我输入 1 时,它也会显示 11, 111 , 132 等等...这就是我遇到 :true 比较器的方式。

I've read other stackflow answers suggesting to write custom filter functions but with the true comparator it looks like I can achieve what I want just by:

我已经阅读了其他建议编写自定义过滤器函数的堆栈流答案,但使用真正的比较器看起来我可以通过以下方式实现我想要的:

<input type="text" class="form-control" id="search.priority"
  title='Priority number to filter by'
  ng-model="search.priority" >

<tr ng-repeat="workflowItem in workflows | filter:search:true">
  <td>{{workflowItem.priority}}</td>

where it does only filter the exact matches. However, obviously it does not pass anything when the input field is empty since nothing matches the empty string.

它只过滤精确匹配的地方。但是,显然当输入字段为空时它不会传递任何内容,因为没有任何内容与空字符串匹配。

My question is: Is there a way I can allow ng-repeat to still display everything when the field is empty while keeping the exact match filter? Appreciate everyone's time!

我的问题是:有没有一种方法可以让 ng-repeat 在字段为空时仍然显示所有内容,同时保持精确匹配过滤器?珍惜大家的时间!

回答by Joel Skrepnek

You'll want to use a custom comparator function. It will allow you to perform a strict comparison except when the predicate is falsy.

您将需要使用自定义比较器函数。它将允许您执行严格的比较,除非谓词为假。

Your markup would then be:

您的标记将是:

 <input type="text" class="form-control" id="search.priority"
  title='Priority number to filter by'
  ng-model="search.priority" >

<tr ng-repeat="workflowItem in workflows | filter:search:exceptEmptyComparator">
 <td>{{workflowItem.priority}}</td>

And define the comparator function on your controller:

并在您的控制器上定义比较器功能:

$scope.exceptEmptyComparator = function (actual, expected) {
    if (!expected) {
       return true;
    }
    return angular.equals(expected, actual);
}

That should do the trick.

这应该够了吧。