日期时间范围自定义筛选器不起作用

时间:2016-11-13 10:25:29

标签: angularjs

我正在尝试按时间范围过滤列表。我正在使用angularjs,bootstrap datetimepicker和moment.js。但是,我无法列出数据。没有自定义过滤器,我可以显示列表,也可以进行简单的文本过滤搜索。我添加了与自定义过滤器相关的代码。

与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;
           };
           });
        }]);

在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>

1 个答案:

答案 0 :(得分:1)

您需要从控制器中取出过滤器,

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;
    };
});