将参数传递给angularjs过滤器 [英] Passing arguments to angularjs filters

查看:215
本文介绍了将参数传递给angularjs过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能传递一个参数过滤功能,以便您可以用任何名称进行筛选?

的东西

  $ scope.weDontLike =功能(项目名称){
    的console.log(参数);
    返回item.name =名字!;
};


解决方案

其实还有另外一个(也许更好的解决方案),你可以使用角度的本地过滤器过滤器,仍然将参数传递给您的自定义过滤器。

考虑以下code:

 < D​​IV NG重复=成群组>
    <李NG重复=朋友的朋友|过滤器:weDontLike(group.enemy.name)>
        <跨度> {{friend.name}}< / SPAN>
    <立GT;
< / DIV>

为了使这项工作你刚才定义过滤器,如下所示:

  $ scope.weDontLike =功能(名称){
    复位功能(朋友){
        返回friend.name =名字!;
    }
}

正如你可以在这里看到,weDontLike实际上返回它在其范围内的参数的另一个功能以及从过滤器来的原始项目。

我花了2天知道你可以做到这一点,还没有看到这一解决方案的任何地方呢。

结帐<一个href=\"http://stackoverflow.com/questions/13464809/reverse-polarity-of-an-angular-js-filter/17811582#17811582\">Reverse一个angular.js过滤的极性看你怎么可以带过滤器使用的其他有用的操作。

Is it possible to pass an argument to the filter function so you can filter by any name?

Something like

$scope.weDontLike = function(item, name) {
    console.log(arguments);
    return item.name != name;
};

解决方案

Actually there is another (maybe better solution) where you can use the angular's native 'filter' filter and still pass arguments to your custom filter.

Consider the following code:

<div ng-repeat="group in groups">
    <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
        <span>{{friend.name}}</span>
    <li>
</div>

To make this work you just define your filter as the following:

$scope.weDontLike = function(name) {
    return function(friend) {
        return friend.name != name;
    }
}

As you can see here, weDontLike actually returns another function which has your parameter in its scope as well as the original item coming from the filter.

It took me 2 days to realise you can do this, haven't seen this solution anywhere yet.

Checkout Reverse polarity of an angular.js filter to see how you can use this for other useful operations with filter.

这篇关于将参数传递给angularjs过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆