如何使用大于ng-repeat的日期过滤ng-repeat

时间:2016-05-26 07:17:31

标签: javascript angularjs angularjs-ng-repeat angular-filters

我想添加过滤器来按日期过滤ng-repeat。今天 例如,要在选中时选中一个复选框,只显示大于今天的日期,并取消选中全部显示 在这里我尝试了:

$scope.gteComparator = function (a, b) {
   return new Date(a) >= new Date(b);
};
$scope.greaterThan = function (prop, val) {
   return prop > val;
}

在视图上:

ng-repeat="row in myModel" | filter: firstFilter| | filter:{ 'DateColumn': (new Date()) }:gteComparator

| filter: greaterThan('DateColumn', new Date())

但没有工作,我该怎么办?

2 个答案:

答案 0 :(得分:1)

在视图上:

ng-repeat="row in myModel | myFilter"

控制器代码:

var nameSpace = angular.module('tst',[]);
nameSpace.controller('MyController', function MyController($scope) {
//controller here
});

nameSpace.filter("myfilter", function() {
  return function(items) {
    var arrayToReturn = [];        
    for (var i=0; i<items.length; i++){
        var date = items[i].date;
        if (date > new Date())  {
            arrayToReturn.push(items[i]);
        }
    }

    return arrayToReturn;
 };
});

答案 1 :(得分:0)

&#13;
&#13;
angular.module('app', []);

angular.module('app').filter('greaterThanToday', () => {
  const now = new Date(); 
  const day = now.getDate();
  const month = now.getMonth();
  const year = now.getFullYear();
  const tomorrow = new Date(year, month, day + 1);
                             
  return (dates) => {
    return dates.filter((date) => date - tomorrow >= 0);
  };
});

angular.module('app').controller('Example', function () {
  this.dates = [];
  
  for (let i = 0; i <= 100; i++) {
    const diff = Math.round(100 * Math.random() - 50) * 24 * 60 * 60 * 1000;
    this.dates.push(new Date(new Date().getTime() + diff));
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Example as Ex">
  <div ng-repeat="date in Ex.dates | greaterThanToday">{{date | date:"yyyy.MM.dd"}}</div>
</div>
&#13;
&#13;
&#13;