2015-04-12 68 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" 

我希望可以幫助別人。

乾杯, 瓦倫丁