繁体   English   中英

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

[英]How to search by date range in 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> 

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

此过滤器将获取您的数据项列表,要过滤的字段(在您的情况下为“ InvoiceDate”),日期范围的开始和结束。 它仅返回位于日期范围边界之间的那些项目。

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

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

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

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

查看此jsfiddle ,它演示了上面的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM