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

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

问题描述

是否可以将参数传递给过滤器函数,以便您可以按任何名称进行过滤?

类似的东西

$scope.weDontLike = function(item, name) {控制台日志(参数);返回 item.name != name;};

解决方案

实际上还有另一种(可能更好的解决方案),您可以在其中使用 angular 的原生过滤器"过滤器,并且仍然将参数传递给您的自定义过滤器.

考虑以下代码:

<li ng-repeat="朋友中的朋友 | filter:weDontLike(group.enemy.name)"><span>{{friend.name}}</span><li>

要完成这项工作,您只需将过滤器定义如下:

$scope.weDontLike = function(name) {返回函数(朋友){返回friend.name != name;}}

正如您在此处看到的,weDontLike 实际上返回另一个函数,该函数在其范围内包含您的参数以及来自过滤器的原始项目.

我花了 2 天时间才意识到您可以做到这一点,还没有在任何地方看到此解决方案.

结帐 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天全站免登陆