valentin
valentin

Reputation: 86

AngularJS ng-repeat ignores filter function

I want to use a filter with ng-repeat. Unfortunately it seems to ignore the result of the function which is attached to the filter.

HTML:

<a ng-repeat="item in date track by $index | filter: filterFunction('2015-09-23',item)" class="item item-icon-left" >
      <div class="listcontent">{{title[$index]}}
          <br> <span class="subinfo">{{item}}</span>
      </div>   
     <i class="iconarrowmore ion-chevron-right"></i>
</a>

JS:

$scope.filterFunction = function (datestamp, element) {
    if (datestamp == element) {
        console.log(datestamp == element);
        return true;
    } else {
        console.log(datestamp == element);
        return false;
    }
};

It returns either true or false when I debug it with console.log but every item still appears in the list.

enter image description here

I really have no clue why its doing that.

Upvotes: 1

Views: 426

Answers (2)

valentin
valentin

Reputation: 86

Okay I found the solution.

If one is using "track by index" with a filter one has to but that behind the filter:

ng-repeat="item in date | filter: filterFunction('2015-09-23') track by $index"

I hope that helps someone.

Cheers, Valentin

Upvotes: 1

dfsq
dfsq

Reputation: 193271

Your filtering function is undefined. Note, that with filter: filterFunction('2015-09-23',item) you immediately execute filterFunction and use its result as filter, which is undefined because your function doesn't return anything.

To fix it make filterFunction return new filter function:

$scope.filterFunction = function(datestamp) {
    return function(element) {
        return datestamp == element;
    };
};

Then HTML part will be the same just you don't need to pass item:

ng-repeat="item in date track by $index | filter: filterFunction('2015-09-23')"

See it working: http://plnkr.co/edit/jLQbgGcLSAxwmiCcYZdP?p=preview

Upvotes: 1

Related Questions