2015-04-12 65 views
1

我想用ng-repeat过滤器。 不幸的是,它似乎忽略了附加到过滤器的函数的结果。AngularJS ng-repeat忽略过滤器函数

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; 
    } 
}; 

当我的console.log调试,但每个项目仍然出现在列表中,则返回true或false。

enter image description here

我真的不知道为什么它这样做。

+0

不只是跳过项目,如果过滤器返回false? 这使得它更容易 – valentin

回答

1

您的过滤功能是undefined。请注意,使用filter: filterFunction('2015-09-23',item),您立即执行filterFunction并将其结果用作筛选器,即undefined,因为您的函数不返回任何内容。

要修复它使filterFunction回新的过滤功能:

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

然后HTML部分将只是你并不需要通过项目相同:

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

看看它的工作:http://plnkr.co/edit/jLQbgGcLSAxwmiCcYZdP?p=preview

+0

谢谢!你的代码与这个例子一起工作,但如果我再次向该列表添加相同的日期,然后通过$ index添加轨道到ng-repeat,它将停止工作。 你知道为什么吗? – valentin

+0

它在控制台中抛出什么错误? – dfsq

+0

无!它只是忽略了过滤器 – valentin

1

好的,我找到了解决方案。

如果一个人使用“通过跟踪指数”带有过滤器一个拥有但该过滤器后:

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

我希望可以帮助别人。

干杯, 瓦伦丁