user3844782 user3844782 - 23 days ago 7
AngularJS Question

Datetime range custom filter not working

I am trying to filter a list by time frame. I am using angularjs, bootstrap datetimepicker and moment.js. But what happens is I am not able to list the data. Without the custom filter I am able show the list and also do simple text filter search. I have added the code related to custom filter.

Code related to filter in Controller

App.controller('ReportController', ['$scope', 'Report','$filter', function($scope, Report,
$filter){
var self = this;

$filter('myfilter')(dateFrom ,dateTo);

App.filter('myfilter', function() {
return function(items, from, to) {
var result = [];
for (var i=0; i<items.length; i++){
var test = new Date(items[i].dateTime.$date);
var month = test.getMonth()+1;
var date = test.getDate();
var year = test.getFullYear();
var hour = test.getHours();
var minute = test.getMinutes();
var second = test.getSeconds();
var newDate = year+"-"+month+"-"+date+""+hour+"-"+minute+"-"+second;
if (newDate > from && newDate < to) {
result.push(items[i]);
}
}
return result;
};
});
}]);


In Html

<div ng-show="Sradioption == 'showSearch2'" class='input-group date' id='datetimepicker6'>
<input type='text' ng-model="dateFrom" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<div ng-show="Sradioption == 'showSearch2'" class='input-group date' id='datetimepicker7'>
<input type='text' ng-model="dateTo" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>

<table class="table table-hover">
<thead>
<tr>
<th>C_Number</th>
<th>Datetime</th>
<th>Reading</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="r in ctrl.reports | filter:search | myfilter:dateFrom:dateTo">
<td>{{r.c_Number}}</td>
<td>{{r.dateTime}}</td>
<td>{{r.reading}}</td>
</tr>
</tbody>
</table>

Answer

You need to take out the filter out of your controller,

App.filter('myfilter', function() {
    return function(items, from, to) {
        var result = [];
        for (var i = 0; i < items.length; i++) {
            var test = new Date(items[i].dateTime.$date);
            var month = test.getMonth() + 1;
            var date = test.getDate();
            var year = test.getFullYear();
            var hour = test.getHours();
            var minute = test.getMinutes();
            var second = test.getSeconds();
            var newDate = year + "-" + month + "-" + date + "" + hour + "-" + minute + "-" + second;
            if (newDate > from && newDate < to) {
                result.push(items[i]);
            }
        }
        return result;
    };
});