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>
Maybe use an
ng-if
?That seems to be the solution.
You can achieve this if you set the filter expression to
''
(orundefined
) - this causes the filter not to be applied - for when yourdisableFilter
is set, or to the actual filter expression otherwise.So, assuming, this toggling variable -
disableFilter
- is a boolean :(with
filterExpression
being whatever the expression you want to filter by). Your specific case would be:EDIT:
To explain how the above works.
||
and&&
return the value of one of its operands.||
and&&
use short-circuit evaluation -true || (anything)
returnstrue
;false && (anything)
returnsfalse
- without evaluating the(anything)
expression.''
is falsy (or useundefined
instead, if it's clearer)And so,
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''
.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}
.Read more about logical operators here
I had a complicated case
prop1
,prop2
selected by user from drop downprop3
) have two value 1 and 2, if user select 2 filter should not be appliedHers is my outcome:
if
model.prop3 == 2 ? ''
filter will not apply otherwise ...We can also use the count of records by using filterdProd
I found the following solution more easy and effective
Here is what I did. First, I had a select control, populated from my controller, with one static item (Select...) with a zero length string value:
Then I applied the filter conditionally on the table. It appears when the filter is null, setting it to undefined clears it:
Make functions and combine with filterExpression.
Example I have a students list as below:
I want to filter students via gender to be boy and filter by name of them.
The first I create a function named "filterbyboy" as following:
Explaination: if not filter name then display all students else filter by input name and gender as 'boy'
Here is a demo How to use and operator in AngularJs example