32

Given a filter method that returns true if some condition is met, is it possible to invoke its opposite in HTML, e.g. to use:

"item in items | filter:!AllDay" 

instead of

"item in items | filter:AllDay" 

? Or do you have to maintain two separate filter methods (one for false and one for true)?

2

4 Answers 4

59

As noted by ENDOH (this SO question is technically a duplicate), you can negate a filter by prepending '!' to the filter string, like this:

filter:'!'+myFilter 

Note that the '!' is quoted. The documentation is not terribly clear on this, and an example there would be helpful.

Sign up to request clarification or add additional context in comments.

5 Comments

When myFilter is a method, not a model, this does not work on angular 1.0.7. The myFilter method is not called at all.
Good pointer about the '!' being quoted - that stumped me for a few minutes (and looks obvious in hindsight)
this was very helpful, for property based filtering instead of strings, it took a bit of trial & error though to figure out: filter:{myPropertyName:'!'+'EverythingOtherThanMe'}
if the value for myFilter is '2', it will block 2, 22, 202, 102, etc. I don't see how you can fix that without writing a function.
@shacker , check this fiddle http://jsfiddle.net/U3pVM/33383/ , why last one is not display in list, event last one id is -12 not -1 ??
32

shacker's answer didn't work for angular 1.0.7, so here's another way to do this:

// You can register this in your AppCtrl if you like, otherwise just use $scope. $rootScope.not = function(func) { return function (item) { return !func(item); } }; 

Then you would do this:

filter:not(myFilterMethod) 

4 Comments

This is a proper answer for 1.2.9 version
This was the best answer for me in angular 1.3
Details on how to add to $rootScope at stackoverflow.com/questions/18880737/….
If you have lodash or underscore you can also do $rootScope.not = _.negate; with benefit being that it works if func has multiple arguments.
24
filter:({day: '!'+AllDay.day}) 

1 Comment

I read on another SO post that this syntax also works: filter:!{day:AllDay.day} But it didn't for me. This was the only way that worked.
0

Another option is to create a new negation filter and pipe it:

 .filter('not', function() { return function(input) { return !input; } }) 
"item in items | filter:AllDay | filter:not" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.