如何使用多个参数调用Angular.js过滤器?

nh2*_*nh2 291 angularjs

文档中我们可以调用像这样的日期过滤器:

{{ myDateInScope | date: 'yyyy-MM-dd' }}
Run Code Online (Sandbox Code Playgroud)

这里date是一个带有一个参数的过滤器.

从模板和JavaScript代码调用带有更多参数的过滤器的语法是什么?

nh2*_*nh2 612

在模板中,您可以使用冒号分隔过滤器参数.

{{ yourExpression | yourFilter: arg1:arg2:... }}
Run Code Online (Sandbox Code Playgroud)

从Javascript,你称之为

$filter('yourFilter')(yourExpression, arg1, arg2, ...)
Run Code Online (Sandbox Code Playgroud)

实际上,orderBy过滤器文档中隐藏了一个示例.


例:

假设您创建了一个可以用正则表达式替换事物的过滤器:

myApp.filter("regexReplace", function() { // register new filter

  return function(input, searchRegex, replaceRegex) { // filter arguments

    return input.replace(RegExp(searchRegex), replaceRegex); // implementation

  };
});
Run Code Online (Sandbox Code Playgroud)

在模板中调用以检查所有数字:

<p>{{ myText | regexReplace: '[0-9]':'X' }}</p>
Run Code Online (Sandbox Code Playgroud)

  • 在HTML模板绑定中{{filter_expression | filter:expression:comparator}},在JavaScript $ filter('filter')中(filter_expression,expression,comparator) (4认同)

Bra*_*avo 10

我在下面提到过我自己也提到了自定义过滤器,如何调用这些有两个参数的过滤器

countryApp.filter('reverse', function() {
    return function(input, uppercase) {
        var out = '';
        for (var i = 0; i < input.length; i++) {
            out = input.charAt(i) + out;
        }
        if (uppercase) {
            out = out.toUpperCase();
        }
        return out;
    }
});
Run Code Online (Sandbox Code Playgroud)

从使用模板的html我们可以像下面那样调用该过滤器

<h1>{{inputString| reverse:true }}</h1>
Run Code Online (Sandbox Code Playgroud)

在这里,如果你看到,第一个参数是inputString,第二个参数是true,它与使用:符号的"反向"组合