2

I have a listing with date range filter for which I'm using ng-table. I could able to filter the name and other string/number fields easily with ng-table. But the date range filter is not seems to be working.

My json data for listing

{  
   "data":[  
      {  
         "cellphone":"24234234234",
         "createddate":"09/09/2014",
         "firstname":"Giacomo",
         "resellerid":"747845473"
      },
      {  
         "cellphone":"24234234234",
         "createddate":"09/02/2010",
         "firstname":"Tomy",
         "resellerid":"747783"
      },
      {  
         "cellphone":"999999",
         "createddate":"09/02/2010",
         "firstname":"Sunny",
         "resellerid":"2312312"
      }
   ]
}

I'm using ng-repeat to traverse this json object.

The filter boxes are outside the table and I'm using following code

 <table class="table display table-striped table-bordered" ng-table="tableParams">

                <tr ng-repeat="customer in $data | filter: id | filter :name 
              |filter :createdfrom>
                <td data-title="'Reseller ID'" sortable="'resellerid'">
                {{customer.resellerid}}
                </td>
                <td data-title="'Reseller Name'" sortable="'firstname'">
                {{customer.firstname}} {{customer.lastname}}
                </td>
                <td data-title="'Created Date'" sortable="'createddate'">
                {{customer.createddate}}
                </td>
                </tr>
  </table>

and in filter boxes which are outside the table

                  <div class="col-sm-2">
                        <input type="text" placeholder="747873" id="exampleInputEmail2"
                            class="form-control" ng-model="id.resellerid">
                    </div>
                    <div class="col-sm-2">
                        <input type="text" placeholder="Enter Name"
                            id="exampleInputPassword2" class="form-control"
                            ng-model="name.firstname">
                    </div>
                    <input  class="form-control" type="text"
                                datepicker-popup="{{format}}" ng-model="createdfrom.createddate"  is-open="opened1" 
                                min-date="minDate" max-date="'2015-06-22'"  datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true"
                                close-text="Close" placeholder="DD/MM/YY" id="date1" > 
                                <span
                                class="input-group-btn">
                                <button type="button" class="btn btn-default"
                                    ng-click="open1($event)">
                                    <i class="glyphicon glyphicon-calendar"></i>
                                </button>
                            </span>
                        </div>

But the date fields are not filtering the json data.

Is there any way to filter the data using dates from "From" and To date fields ?

Any help/hint would be greately appreciated.

Thanks jayesh

3 Answers 3

1

I created this one using UI-Bootstrap date picker. See if this solves your problem.

// Code goes here

var myapp = angular.module('NgTableExample', ['ngAnimate', 'ui.bootstrap', 'ngTable']);

function parseDate(input) {
  return Date.parse(input);
}

myapp.filter("dateRangeFilter", function() {
  return function(items, from, to) {
    var df = parseDate(from);
    var dt = parseDate(to);
    var result = [];
    for (var i = 0; i < items.length; i++) {
      var date_bet = items[i].datetime;
      if (date_bet > df && dt > date_bet) {
        result.push(items[i]);
      }
    }
    return result;
  };
});

myapp.controller("ExampleCtrl", function($scope, $filter, NgTableParams) {

  var self = this;
  var data = [{
    name: "Moroni",
    age: 50,
    datetime: 1450562394000
  }, {
    name: "Simon",
    age: 43,
    datetime: 1450562394000
  }, {
    name: "Jacob",
    age: 27,
    datetime: 1450648794000
  }, {
    name: "Nephi",
    age: 29,
    datetime: 1450648794000
  }, {
    name: "Christian",
    age: 34,
    datetime: 1450475994000
  }, {
    name: "Tiancum",
    age: 43,
    datetime: 1450475994000
  }, {
    name: "Jacob",
    age: 27,
    datetime: 1450475994000
  }];

  self.sensorTableData = new NgTableParams({
    count: 7
  }, {
    dataset: data
  });

  $scope.today = function() {
    $scope.dt2 = new Date(2015, 11, 26);
    $scope.dt1 = new Date(2015, 11, 17);

  };



  $scope.today();
  $scope.toggleMin = function() {
    $scope.minDate = $scope.minDate ? null : new Date();
  };
  $scope.toggleMin();
  $scope.maxDate = new Date(2020, 5, 22);

  $scope.open1 = function($event) {
    $scope.status1.opened = true;
  };

  $scope.open2 = function($event) {
    $scope.status2.opened = true;
  };

  $scope.setDate = function(year, month, day) {
    $scope.dt1 = new Date(year, month, day);
    $scope.dt2 = new Date(year, month, day);

  };

  $scope.dateOptions = {
    formatYear: 'yy',
    startingDay: 1
  };

  $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
  $scope.format = $scope.formats[0];

  $scope.status1 = {
    opened: false
  };

  $scope.status2 = {
    opened: false
  };


});
<!DOCTYPE html>
<html>

<head>
  <link data-require="bootstrap-css@*" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script>
  <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>
  <link rel="stylesheet" href="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.css">
  <script src="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="NgTableExample">
  <h1>Date Range Filter For Ng-table!</h1>

  <div ng-controller="ExampleCtrl as exc">
    <h4>From Date</h4>
    <p class="input-group">
      <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt1" is-open="status1.opened" max-date="maxDate" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close" />
      <span class="input-group-btn">
          <button type="button" class="btn btn-default" ng-click="open1($event)"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
    </p>
    <h4>To Date</h4>
    <p class="input-group">
      <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt2" is-open="status2.opened" max-date="maxDate" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close" />
      <span class="input-group-btn">
          <button type="button" class="btn btn-default" ng-click="open2($event)"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
    </p>

    <div>
      <table ng-table="exc.sensorTableData" class="table table-condensed table-bordered table-striped">
        <tr ng-repeat="row in $data | dateRangeFilter:dt1:dt2">
          <td data-title="'Name'" sortable="'name'">{{row.name}}</td>
          <td data-title="'Age'" sortable="'age'">{{row.age}}</td>
          <td data-title="'Date'" sortable="'age'">{{row.datetime | date:'dd-MMMM-yyyy'}}</td>
        </tr>
      </table>
    </div>
  </div>
</body>

</html>

Sign up to request clarification or add additional context in comments.

1 Comment

i was trying to implement your code but it is not working for me. It is showing undefined for items
0

Are you sure that ng-model="createdfrom.createddate" attaches any data to $scope?

Try adding <pre>createdfrom.createddate: {{ createdfrom.createddate }}</pre> to see if that datepicker directive changes value in $scope.

EDIT: Check working example: http://jsfiddle.net/ulfryk/vbvyt8we/


EDIT2:

I found the answer:

<tr ng-repeat="customer in $data | filter: id | filter :name 
          |filter :createdfrom>

you missed " after |filter :createdfrom and before > :D


EDIT3:

datepicker holds value of type Date in model and it's formatted String representation in view layer. So you maybe need some other directive or filter to translate that model data into formatted string, or to pass view value to some other field in model:

yourModule.directive('viewValueModel', [
    '$parse',
    function ($parse) {
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, ngModelCtrl) {
                ngModelCtrl.$viewChangeListeners.push(function () {
                    $parse(attrs.viewValueModel).assign(scope, ngModelCtrl.$viewValue);
                });
            }
        };
    }
]);

and use it like this:

<input
    class="form-control"
    type="text"
    datepicker-popup="{{format}}"

    ng-model="someFakeModelPlaceholder"
    view-value-model="createdfrom.createddate"

    is-open="opened1"
    min-date="minDate"
    max-date="'2015-06-22'"
    datepicker-options="dateOptions"
    date-disabled="disabled(date, mode)"
    ng-required="true"
    close-text="Close"
    placeholder="DD/MM/YY"
    id="date1"> 

5 Comments

It seems that my date picker is not at all giving the date in correct format. I used bootstrap date picker - angular-ui.github.io/bootstrap - When I selected 09/02/2010 in datepicker, selected date is shown like this - createdfrom.createddate: "2010-02-08T18:30:00.000Z" I have formatted the datepicker date in my controller "$scope.format = 'dd/MM/yyyy';" and it is displaying the date in text box perfectly. What could be the issue ?
Added edit to answer - it's probably just HTML mistake - lack of " before > in opening <tr> tag..
Added 3rd edit to answer 2nd and 3rd one together should fix everything :)
I have copied a part of the filter, the quotes are already there.
Ok. So check the third EDIT. This should help :)
0

Following up on Himanshu Jain example, I had to tweak it to get it working.

(function () {
'use strict';
angular.module('app').filter("dateRangeFilter", ['$filter', function ($filter) {
    return function (items, from, to) {
        var df = from;
        var dt = to;
        var result = [];
        for (var i = 0; i < items.length; i++) {
            var date_bet = parseDate(items[i].StartDate);
            if (date_bet >= df && dt >= date_bet) {
                result.push(items[i]);
            }
        }
        return result;
    };
}]);

})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.