3

I want to add filter to filter ng-repeat by date greater than today.
For example to have a checkbox when check it to display only dates greater than today and uncheck display all.
Here what I tried:

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

On the view:

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

or

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

But none work, what should I do?

1110
  • 7,829
  • 55
  • 176
  • 334

2 Answers2

1

On the view:

ng-repeat="row in myModel | myFilter"

Controller code:

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;
 };
});
Avantika Saini
  • 792
  • 4
  • 9
0

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));
  }
});
<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>
sielakos
  • 2,406
  • 11
  • 13