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

313

根据文档,我们可以像这样调用过滤器date

As from the documentation, we can call a filter such as date like this:
{{ myDateInScope | date: 'yyyy-MM-dd' }}

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

无论是从模板还是JavaScript代码中调用带有多个参数的过滤器的语法是什么?

6个回答

643
在模板中,您可以使用冒号来分隔筛选器参数。
{{ yourExpression | yourFilter: arg1:arg2:... }}

从Javascript调用它时,您称其为

$filter('yourFilter')(yourExpression, arg1, arg2, ...)

实际上,在orderBy过滤器文档中,隐藏着一个例子。


例子:

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

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

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

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

  };
});

模板中用于屏蔽所有数字的调用:

<p>{{ myText | regexReplace: '[0-9]':'X' }}</p>

4
HTML模板绑定中的表达式为:{{ filter_expression | filter:expression:comparator }} 相应的JavaScript代码为:$filter('filter')(filter_expression, expression, comparator)。 - Roman Sklyarov
@pulkitsinghal 你是什么意思?在JSFiddle或Plunker中展示你的有问题的代码。 - Roman Sklyarov
1
@ObiOnuorah 好的,已经将Coffeescript翻译成了Javascript。 - nh2
1
好东西。为什么这个答案不在列表的顶部? - thethakuri
@nh2,您能否更新您的答案,加入srox00的建议?JavaScript应该是$filter('yourFilter')(yourExpression, arg1, arg2, ...) - Dylanthepiguy
显示剩余3条评论

11

我在下面提到了自定义筛选器,也说明了如何调用这些具有两个参数的筛选器。

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;
    }
});

我们可以通过模板从html中如下调用该过滤器:

<h1>{{inputString| reverse:true }}</h1>

如果您看到这里,第一个参数是 inputString,第二个参数是 true,使用 : 符号与 "reverse" 组合在一起。


4
如果你想在ng-options中调用你的过滤器,代码如下所示:
ng-options="productSize as ( productSize | sizeWithPrice: product )  for productSize in productSizes track by productSize.id"

筛选器名称为sizeWithPriceFilter,它有两个参数:product和productSize。


1

like this:

var items = $filter('filter')(array, {Column1:false,Column2:'Pending'});

0

如果您需要对过滤器进行两次或更多次操作,可以将它们链接在一起:

{{ value | decimalRound: 2 | currencySimbol: 'U$' }} 
// 11.1111 becomes U$ 11.11

可能重复:https://dev59.com/d2Qo5IYBdhLWcg3wOdJa - sjokkogutten
1
不回答“如何使用多个参数调用Angular.js过滤器”的问题(而不是“如何调用多个过滤器?”) - rom99

-1
在这段代码中,jsondata是我们的数组,在return函数中我们会检查jsondata中是否存在'version'。
var as = $filter('filter')(jsondata, function (n,jsondata){
   return n.filter.version==='V.0.3'
});

console.log("name is " + as[0].name+as[0]); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接