0

I am using a filter in a ng-repeat to separate a list of Jsons in two sub-lists: One with Present-past items and other with future items. The json has a key called "dateFrom" which i compare with the actual date to determine in which list this item will appear.

But, despite the filter function only uses the "dateFrom" key to determine this, if i modify some other keys as well, the filter changes.

I made a quick jsFiddle to show the problem:

https://jsfiddle.net/1j2p2hbg/1/

The filtering function is:

$scope.isPast = function(item)
{
var now = new Date();
return (item.dateFrom <= now);
}

We have there 4 elements... 3 of them have the actual date and other has a future date. The "isPast" function ONLY checks the "dateFrom" attribute, but if i change the attributes "keyBoolOne" and "keyBoolTwo", it will affect the filter as well.

Anyone could tell me why?

Thanks in advance!

TRDrake
  • 202
  • 1
  • 3
  • 13

1 Answers1

2

Reversing the polarity of filters is problematic in AngularJS. It is also not mentioned in documentation but you should use

<div ng-repeat="item in list | filter: '!'+keyBoolOne">

instead of

<div ng-repeat="item in list | filter: !keyBoolOne">

But in your case, this still won't work because you are using function instead of attribute of objects.

Alternative 1

To avoid this kind of unclear mistakes, you may define secondary filter function like follows;

$scope.isFuture = function(item){
    return !$scope.isPast(item);
}

and use it as filter for your second sub-list.

<div ng-repeat="item in list | filter: isFuture">

Alternative 2

If you don't want to define additional function for each filter (which may negated), you can define "not" function on your own.

$scope.not = function(filterFunc) {
    return function (item) { 
        return !filterFunc(item); 
    }
};

And use it as follows (in anywhere / any sublist);

<div ng-repeat="item in list | filter: not(isPast)">

References to check;

Reverse the polarity of AngularJS filters

Negation on filter

Community
  • 1
  • 1
Tuğca Eker
  • 1,493
  • 13
  • 20
  • Hi man, thanks for answering! In my actual project i have a similar problem, where some items does not appear in any of the 2 lists. The json is pretty the same but i cannot replicate it yet. Is there a way to pass only the "item.dateFrom" to the filter so it will completely ignore all the rest of the attributes? Thanks! – TRDrake Jan 23 '17 at 15:36