【问题标题】:Use Exclamation Point as First Character with AngularJS Filter使用感叹号作为 AngularJS 过滤器的第一个字符
【发布时间】: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


【解决方案1】:

我最终使用了我在这篇文章中修改的指令。 https://stackoverflow.com/a/15346236/2908576

MyApp.directive("noNegation", [function() {
    return {
        require: "ngModel",
        link: function(scope, element, attrs, ngModelController) {
            ngModelController.$parsers.push(function(data) {
                while (data.indexOf("!") == 0)
                    data = data.substring(1);
                return data;
            });
        }
    };
}]);

它忽略输入开头的所有感叹号。这意味着搜索 !!!MyApplication 仍会返回 MyApplication,即使名称中没有感叹号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 2018-01-21
    • 1970-01-01
    • 2020-06-14
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多