【发布时间】:2017-04-20 03:36:54
【问题描述】:
我正在使用 ng-repeat 过滤 AngularJS 中的对象列表:
<tr ng-repeat="application in page.applications | filter: {DisplayName:page.ApplicationSearchValue}">
{{application.DisplayName}}
</tr>
如果用户将感叹号作为搜索框中的第一个字符,那么 Angular 会将其解释为否定符号。所以!MyApplication 返回除 MyAppliction 之外的所有应用程序。
我尝试使用自定义函数作为 the Angular documentation for filter 中的描述,但感叹号始终无法进入函数。
我发现代码正在通过AngularJS source code中的以下函数,这基本上是强制感叹号得到特殊处理:
function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
var actualType = getTypeForFilter(actual);
var expectedType = getTypeForFilter(expected);
if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
.....
我目前的“解决方案”是将过滤器对象更改为:
filter: {DisplayName:(page.ApplicationSearchValue.indexOf('!') == 0 ? page.ApplicationSearchValue.substring(1) : page.ApplicationSearchValue)}
但 QA 发现如果有人使用 !! 启动搜索框仍然会出现问题,这只是时间问题。
有处理这种情况的通用模式吗?
【问题讨论】:
-
向我们展示您如何尝试使用自定义函数。
-
ctrl.filterFunc = function(actual, expected) { expected = expected.indexOf('!') == 0 ? expected.substring(1) : expected; return actual.toLowerCase().indexOf(expected) != -1; }但是expected的值从不包含感叹号。 -
不要通过比较器。传递一个函数作为过滤器的唯一参数。如果元素应该被过滤器接受,则使此函数返回 true,否则返回 false。
标签: angularjs angularjs-filter