如何在AngularJs中按日期范围搜索

时间:2017-12-24 13:01:13

标签: javascript angularjs

我是AngularJs的新手,我正在创建搜索模板,选择发件人日期和收件人日期,当我点击搜索按钮时,我需要此范围的结果

点击搜索按钮后,需要填充结果

table td,
th {
  font-size: 11px;
  font-weight: 500;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/assets/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
  <div class="clearfix" ng-controller="tableDataCtrl">
    From : <input type="date" id="fromDate" name="fromDate"><br> To : <input type="date" id="toDate" name="toDate"><br>
    <input type="button" id="searchButton" value="Search"><br>
    <table class="table">
      <thead>
        <tr>
          <th ng-repeat="th in tableHeader">
            {{th}}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="tr in tableData">
          <td ng-repeat="td in tr">
            {{td}}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

<script>
  var app = angular.module('myApp', []);
  app.controller('tableDataCtrl', function tableDataCtrl($scope, $http) {
    // $http.get("https://api.myjson.com/bins/uwz13").then(function (response) {

    $http.get("https://api.myjson.com/bins/cl913").then(function(response) {
      // console.log(response);
      $scope.tableData = response.data.data;
      $scope.tableHeader = response.data.header;
    });
  });
</script>

1 个答案:

答案 0 :(得分:1)

AngularJS中您想要做的最佳做法是创建一个这样的过滤器:

app.filter("dateRange", function() {
    return function(items, fieldName, fromDate, toDate) {
        var from = new Date(fromDate);
        var to = new Date(toDate);
        var itemsInRange = [];
        for(var i = 0; i < items.length; i++) {
            var date = new Date(items[i][fieldName]);
            if(from <= date && date <= to)
                itemsInRange.push(items[i]);
        }
        return itemsInRange;
    };
});

此过滤器会将您的数据项列表,字段过滤(&#34; InvoiceDate&#34;在您的情况下),日期范围开始和结束。它仅返回落在日期范围边界之间的项目。

它可以直接在HTML中使用(每当参数更改时刷新):

<tr ng-repeat="tr in tableData | dateRange: 'InvoiceDate':fromDate:toDate">

或者您可以在JavaScript中以编程方式使用它(按需刷新):

$filter('dateRange')($scope.tableData, 'InvoiceDate', fromDate, toDate);

查看此jsfiddle,演示上述解决方案。