MOSH
MOSH

Reputation: 37

How to filter data by date range in angularjs?

I'm new to angularjs and I could n't find any COMPLETE solution for filtering data with date range picker in angular. Following code is what I did after spending 2 days for searching. What i want is to filter following data based on their release date by using date range picker.

HTML:

 <!DOCTYPE HTML>
    <html ng-app="example">
        <head lang="en">
            <meta charset="utf-8">
            <title>Example</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">

            <script src="js/jquery-1.11.3.min.js"></script>
            <script src="js/angular.js"></script>
            <script src="js/moment.min.js"></script>
            <script src="js/daterangepicker.js"></script>
            <script src="js/angular-daterangepicker.min.js"></script>
            <script src="js/bootstrap.min.js"></script>

            <script src="app/app.js"></script>

            <link href="css/bootstrap.min.css" rel="stylesheet">
            <link href="css/daterangepicker.css" rel="stylesheet">
        </head>
        <body ng-controller="mainController as vm" >
            <br><br>
            <div class="container">
                <div class="row">
                    <div class="col-lg-8 col-lg-offset-2">
                        <div class="panel panel-primary">
                            <div class="panel-heading">
                                <h3>Product List</h3>
                            </div>
                            <div class="row">
                                <br>
                                <div class="col-lg-3 text-right">
                                    <h4>Filter by date :</h4>
                                </div>
                                <div class="col-lg-6">
                                    <input date-range-picker name="daterange3" 
                                           class="form-control date-picker" type="text"
                                           ng-model="date" options="opts" clearable="true" required/>
                                </div>
                            </div>
                            <div class="panel-body">
                                <table  class="table table-responsive">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>Code</th>
                                            <th>Availabel</th>
                                            <th>Price</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr ng-repeat="product in vm.products">
                                            <td>{{product.productName}}</td>
                                            <td>{{product.productCode}}</td>
                                            <td>{{product.releaseDate | date }}</td>
                                            <td>{{product.price | currency}}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </body>
    </html>

App.js

    (function (){
    "use strict";
    angular
        .module("example",["daterangepicker"])
        .controller("mainController",["$scope",mainController]);


    function mainController($scope)
    {
        var vm = this;

        vm.products = [
            {
                "productId": 1,
                "productName": "Leaf Rake",
                "productCode": "GDN-0011",
                "releaseDate": "2015-12-15T22:00:00.000Z",
                "description": "Leaf rake with 48-inch wooden handle.",
                "cost": 9.00,
                "price": 19.95,
                "category": "garden",
                "tags": ["leaf", "tool"],
            },
            {
                "productId": 2,
                "productName": "Garden Cart",
                "productCode": "GDN-0023",
                "releaseDate": "2015-12-16T22:00:00.000Z",
                "description": "15 gallon capacity rolling garden cart",
                "cost": 20.00,
                "price": 32.99,
                "category": "garden",
                "tags": ["barrow", "cart", "wheelbarrow"],
            },
            {
                "productId": 5,
                "productName": "Hammer",
                "productCode": "TBX-0048",
                "releaseDate": "2015-12-17T22:00:00.000Z",
                "description": "Curved claw steel hammer",
                "cost": 1.00,
                "price": 8.99,
                "category": "toolbox",
                "tags": ["tool"],
            },
            {
                "productId": 8,
                "productName": "Saw",
                "productCode": "TBX-0022",
                "releaseDate": "2015-12-18T22:00:00.000Z",
                "description": "15-inch steel blade hand saw",
                "cost": 6.95,
                "price": 11.55,
                "category": "garden",
                "tags": ["garden", "mower"],
            },
            {
                "productId": 10,
                "productName": "Video Game Controller",
                "productCode": "GMG-0042",
                "releaseDate": "2015-12-19T22:00:00.000Z",
                "description": "Standard two-button video game controller",
                "cost": 2.22,
                "price": 35.95,
                "category": "gaming",
                "tags": ["gaming", "controller", "video game"],
            }
        ];
        $scope.date={
            startDate: moment().subtract(1, "days"),
            endDate: moment()
        };
        $scope.date2={
            startDate: moment().subtract(1, "days"),
            endDate: moment()
        };
        $scope.opts={
            ranges: {
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()]
            }
        };
        $scope.setStartDate = function () {
            vm.date.startDate = moment().subtract(4, "days");
        };
        $scope.setRange = function () {
            vm.date = {
                startDate: moment().subtract(5, "days"),
                endDate: moment()
            };
        };
        $scope.$watch('date', function(newDate) {
            console.log('New date set: ', newDate);
        }, false);
    }
}());

Thank you guys ...

Upvotes: 1

Views: 6004

Answers (2)

Anchel Benedi
Anchel Benedi

Reputation: 41

I had the same issue with inputs and this was my solution:

In HTML I use two date inputs

        <div class="col-md-3 form-group">
            <input type="date" class="form-control" ng-model="from">
        </div>
        <div class="col-md-3 form-group">
            <input type="date" class="form-control" ng-model="to">
        </div>

In app.js:

    app.filter("dateFilter", function() {
       return function datefilter(items, from, to) {
       var result = [];
       angular.forEach(items, function(value){
           if (Date.parse(value.date) > Date.parse(from) && Date.parse(to) > Date.parse(value.date))  {
               result.push(value);
            }
        });
        return result;
        };
    });

In the controller I set the inputs to the last month:

    $scope.from = new Date();
    $scope.from.setMonth($scope.from.getMonth()-1);
    $scope.to = new Date();

And in ng-repeat

        <tr ng-repeat="item in items | dateFilter:from:to">
            <td>{{item.name}}</td>
            <td>{{item.date}}</td>
        </tr>

That is working for me, I hope to be usefull.

Upvotes: 3

user5698801
user5698801

Reputation: 574

In angular, you can user pipeline operator to chain the operations. As belows,

<tr ng-repeat="product in vm.products | filter:date as results">

The complete document please refer to https://docs.angularjs.org/api/ng/directive/ngRepeat

Upvotes: 1

Related Questions