angularJS ng-repeat with filter,其日期大于数组

时间:2016-05-27 13:06:54

标签: angularjs filter angularjs-ng-repeat

我看了很多地方,似乎无法找到我要找的东西。它可能很简单,但我对角度更新,似乎无法弄明白。

ng-repeat工作正常,但我想过滤掉某些值。

我有一个带有ng-repeat数据的页面(参见下面的数据对象),我想只包含当前日期>的页面。数组中的项值(日期)。

     vm.newsItems= [
       {
           ID: '1',
           date: '5/12/2016',
           newsTitle: 'This is news story header 1',
           newsText: 'This is news Story Text 1.  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
       },
       {
           ID: '2',
           date: '5/30/2016',
           newsTitle: 'This is news story header 2',
           newsText: 'This is news Story Text 2.  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
       }
页面上的

代码:

    <div class="box effect8" ng-repeat="newsItem in vm.newsItems">
                <h3>{{newsItem.newsTitle}}</h3>
                {{newsItem.newsText}}
            </div>

2 个答案:

答案 0 :(得分:3)

尝试添加带有filter $filter的谓词来过滤掉项目:

newsItem in vm.newsItems | filter: getItemsFromThePast()

vm.getItemsFromThePast =  function(item) {
  var today = new Date();
  return item.date < today;
}

我在这里假设两件事:

  • 使用当前日期表示new Date()
  • 对象的属性date是实际的Date对象,如果它们是日期格式的字符串,则必须先将它们转换为Date对象

答案 1 :(得分:0)

检查Codepen。这对你有用。我已将日期字符串转换为Object并将其与过滤器一起使用

var myApp = angular.module('myApp', []);

 myApp.controller('MyController', function ($scope) {

 $scope.newsItems= [
   {
       ID: '1',
       date: '5/12/2016',
       newsTitle: 'This is news story header 1',
       newsText: 'Some text.'
   },
   {
       ID: '2',
       date: '5/30/2016',
       newsTitle: 'This is news story header 2',
       newsText: 'Some text.'
   }
];

 angular.forEach($scope.newsItems, function(value,key) {
  value.date = new Date(value.date);
 });

 $scope.filterDate =  function(newsItem) {
  var today = new Date();   
  return newsItem.date < today;
 }

});