使角度过滤器有条件 [英] Making an angular filter conditional

查看:28
本文介绍了使角度过滤器有条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用文本输入来过滤项目列表.我想这样做,当设置了特定变量时,无论文本输入是什么,列表都不会过滤.关于我如何做到这一点的任何建议?

I'm currently using a text input to filter a list of items. I'd like to make it so when a particular variable is set, the list doesn't filter, regardless of what the text input is. Any advice on how I can accomplish this?

<a ng-repeat="set in data | filter: { value: search }" data-id="{{set.id}}" ng-mousedown="setBox(set)" ng-mouseover="setSelected(set, $event)" ng-bind-html="set.value | trustHTML"></a>

推荐答案

如果将过滤器表达式设置为 ''(或 undefined),则可以实现此目的 - 这导致不应用过滤器 - 当您的 disableFilter 被设置时,或者其他情况下的实际过滤器表达式.

You can achieve this if you set the filter expression to '' (or undefined) - this causes the filter not to be applied - for when your disableFilter is set, or to the actual filter expression otherwise.

编辑 2:另一个答案(下面是 @Ryan)更简单也更容易理解.现在不记得是它最初对我不起作用还是我根本没有想到这种更简单的方法.

EDIT 2: The other answer (below by @Ryan) is simpler and easier to understand. Can't remember now whether it didn't work for me initially or I simply didn't think of this simpler way.

所以,假设这个切换变量 - disableFilter - 是一个布尔值:

So, assuming, this toggling variable - disableFilter - is a boolean :

<a ng-repeat="set in data | filter: (!disableFilter || '') && filterExpression">

(filterExpression 是您要过滤的任何表达式).您的具体情况是:

(with filterExpression being whatever the expression you want to filter by). Your specific case would be:

<a ng-repeat="set in data | filter: (!disableFilter || '') && {value: search}">

解释上面的工作原理.

  1. 请记住,||&& 返回其操作数之一的值.
  2. ||&& 使用短路评估 - true ||(任何) 返回 true;false &&(anything) 返回 false - 不计算 (anything) 表达式.
  3. '' 是假的(或者使用 undefined 代替,如果它更清楚)
  1. Remember that || and && return the value of one of its operands.
  2. || and && use short-circuit evaluation - true || (anything) returns true; false && (anything) returns false - without evaluating the (anything) expression.
  3. '' is falsy (or use undefined instead, if it's clearer)

所以,

disableFilter === true 时,!disableFilter === false,因此 || 的第二个操作数 - 空字符串 '' - 被评估(它是假的),并且 (!disableFilter || '') 返回 '' - 一个假值,它短-对 && 操作进行循环,并且不评估 && 的第二个操作数.因此表达式的返回值是 ''.

when disableFilter === true, !disableFilter === false, thus the second operand of || - the empty string '' - is evaluated (it's falsy), and (!disableFilter || '') returns '' - a falsy value, which short-circuits the && operation and does not evaluate the second operand of &&. The return value of the expression is thus ''.

disableFilter === false, !disableFilter === true 时,使 || 操作短路,然后第二个&& 的操作数被评估并返回.因此表达式的返回值是 {value: search}.

when disableFilter === false, !disableFilter === true, which short-circuits the || operation, then the second operand of && is evaluated and returned. The return value of the expression is thus {value: search}.

在此处阅读有关逻辑运算符的更多信息

这篇关于使角度过滤器有条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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