Trouble in filter table data between two selected dates using angularjs
Asked Answered
L

2

2

I am working on filtering table content based on two selected dates. It do filter the date but result is not correct. dateRange Filter is written in controller.

ProductionController

angular.module('app').controller('ProductionController',
    ['$scope','$state','ProductionService','FarmerRepository', 
     function(scope,state,ProductionService,FarmerRepository) {
     fetchAllUsers();
     function fetchAllUsers() {
     ProductionService.fetchAllUsers().then(function(d) {
     produceList = d;
     scope.produceList = produceList;
     }, function(errResponse) {
     console.error('Error while fetching produceList');
     });
     };

    //this is custom filter

    .filter('dateRange', function() {
    return function(produceList, fromDate, toDate) {    
    if(fromDate && toDate){
    var filtered = [];
    angular.forEach(produceList, function(items) {
        if (items.produceDate > Date.parse(fromDate) && items.produceDate < Date.parse(toDate))
            filtered.push(items);
    });
    return filtered;
    }
    else
    return produceList;
    }})

view.html

<datepicker date-format="dd/MM/yyyy" >
   <input class="form-control" name="from_date"
   type="text" ng-model="from_date" required />
</datepicker>



<datepicker date-format="dd/MM/yyyy" selector="form-control">
    <input class="form-control" name="to_date"
    type="text" ng-model="to_date" required />
</datepicker>


 <tr ng-repeat="item in produceList |dateRange:from_date:to_date|filter:search">

Edit: Order of script

<script ng-src=".js/moment.js"></script>
<script ng-src="./js/alasql.min.js"></script>
<script ng-src="./js/xlsx.core.min.js"></script>
<link ng-href="./css/page.css" rel="stylesheet" />
<link ng-href="./css/angular-datepicker.css" rel="stylesheet"
type="text/css" />
<link ng-href="./css/page.css" rel="stylesheet" />

Please check the converted dates value.produceDate when converted to number format it doesnot lie between from and to date.hence here filtering is not happening.

angular.module('app', ['720kb.datepicker']).controller('MyController', function ($scope) {  
  var formatStr = 'DD/MM/YYYY';
  $scope.from_date = moment("2017-05-02").format(formatStr);
  $scope.to_date = moment("2017-05-10").format(formatStr);  
  
 $scope.produceList = [{
 	"itemName": "Mango",
 	"produceDate": 1493360722000,
 	"produceId": 90
 }, 
 {
 	"itemName": "Banana",
 	"produceDate": 1493290754000,
 	"produceId": 89
 }, 
 {
 	"itemName": "Grapes",
 	"lastDateForBid": 1493510400000,
 	"produceDate": 1493099760000,
 	"produceId": 83
 },
  {
 	"itemName": "Apple",
 	"produceDate": 1490615680000,
 	"produceId": 66
 },
 {
 	"itemName": "Grapes",
 	"produceDate": 1490615515000,
 	"produceId": 65
 }]
 })

 .filter('dateRange', function() {
    var formatStr = 'DD/MM/YYYY';
    return function(produceList, fromDate, toDate) {    
      if(fromDate && toDate){
        var filtered = [];
        angular.forEach(produceList, function(items) {        
            if (items.produceDate > Date.parse(moment(fromDate, formatStr)) && items.produceDate < Date.parse(moment(toDate, formatStr)))
                filtered.push(items);
        });
        return filtered;
      }
      else
        return produceList;
}})
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-datepicker/2.1.19/angular-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-datepicker/2.1.19/angular-datepicker.min.css" rel="stylesheet" type="text/css" />

<div ng-app='app' ng-controller="MyController">        
<div>
fromDate: <datepicker date-format="dd/MM/yyyy"><input ng-model="from_date" type="text"/></datepicker>     
</div>            
<div>
toDate: <datepicker date-format="dd/MM/yyyy"><input ng-model="to_date" type="text"/></datepicker>       
</div>  
search:
<br/>
<input type='text' ng-model='search'/>
    <ul>
      <li ng-repeat="item in produceList | dateRange:from_date:to_date |filter:search">
        {{item | json}}
      </li>
    </ul>
</div>
Lashonda answered 26/4, 2017 at 6:46 Comment(14)
Possible duplicate of ng-repeat filtering data by date rangeCommunicate
What do you mean with: 'dateRange Filter is written in controller'? You must do angular.module('farmer').filter('dateRange', function(){...}Strongbox
Are you sure items.produceDate is in the correct format? Maybe you just need to do Date.parse(items.produceDate) to compare.Strongbox
@PedroPerez y to parse it (items.produceDate)Lashonda
@PedroPerez Actually its comparing but finally displaying entire table or it doesnot display onlyLashonda
your code is working fine for me, check my exampleMarybethmaryellen
@Marybethmaryellen yeah everything working fine in plunker.But am getting moment not definedLashonda
which line is getting highlighted on that error, make sure that your angular script is loaded after monent js script.Marybethmaryellen
At this line if (items.produceDate > Date.parse(moment(fromDate, formatStr)) && items.produceDate < Date.parse(moment(toDate, formatStr)))Lashonda
Move moment.js to top of all scriptsMarybethmaryellen
place <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script> at the first line inside head tag.Marybethmaryellen
Yes sravan,Placed and checked it..Again same issue.I am not getting wht to do.Lashonda
@Marybethmaryellen . I have a doubt.When converting to number format will there be any issue.Because when produceDate is inbetween` from and to` date in date format and when the same converted to number format produceDate will be smaller than from and to date..?whyLashonda
Let us continue this discussion in chat.Marybethmaryellen
K
1

I made some modification at your .filter and used this datepicker directive:

angular.module('app', ['720kb.datepicker']).controller('MyController', function ($scope) {    
  $scope.from_date = '02/05/2017';
  $scope.to_date = '10/05/2017';  
  
  $scope.produceList = [
    {itemName:'Tom', produceDate: Date.parse(new Date(2017, 5, 9))},
    {itemName:'Sam', produceDate: Date.parse(new Date(2017, 5, 10))},
    {itemName:'Paul', produceDate: Date.parse(new Date(2017, 5, 11))},
    {itemName:'Henry', produceDate: Date.parse(new Date(2017, 5, 12))},
  ]

}).filter('dateRange', function() {
    
    var fromStr2Date = function(date){
      var days = +date.substr(0, 2);
      var month = +date.substr(3, 2);
      var year = +date.substr(6, 4);
      return new Date(year, month, days);
    }
    
    return function(produceList, fromDate, toDate) {    
      if(fromDate && toDate){
        var filtered = [];
        angular.forEach(produceList, function(items) {        
            if (items.produceDate > Date.parse(fromStr2Date(fromDate)) && items.produceDate < Date.parse(fromStr2Date(toDate)))
                filtered.push(items);
        });
        return filtered;
      }
      else
        return produceList;
}})
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-datepicker/2.1.19/angular-datepicker.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-datepicker/2.1.19/angular-datepicker.min.css" rel="stylesheet" type="text/css" />

<div ng-app='app' ng-controller="MyController">        
<div>
fromDate: <datepicker date-format="dd/MM/yyyy"><input ng-model="from_date" type="text"/></datepicker>     
</div>            
<div>
toDate: <datepicker date-format="dd/MM/yyyy"><input ng-model="to_date" type="text"/></datepicker>       
</div>  
search:
<br/>
<input type='text' ng-model='search'/>
    <ul>
      <li ng-repeat="item in produceList | dateRange:from_date:to_date |filter:search">
        {{item | json}}
      </li>
    </ul>
</div>
Kotta answered 15/5, 2017 at 6:35 Comment(13)
Check is my code snippet work as you expect or only your code not work?Kotta
Run code snippet again, may be you forget to clear additional search filter?Kotta
You can simple copy paste my answer into your project or create plunker for your question to figure out what is wrong with it.Kotta
No I edited my code snippet (from my answer), now it is exactly like your question's code in terms of html.Kotta
Check order at which you add momen.js it should be added at first. Also look at it's site, where you can learn how to install it.Kotta
No, you can install it via cdn or manually. Check <script> order!Kotta
Place it to the top, with link exactly same as in my answer: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>Kotta
Create fully completed plunker, not like previous stubKotta
You already have working solution! The only one you need to do is to create plunker with included moment.js, to figure out, why it is not working for you. Without it I can't help you, because my answer works, I can't reproduce any of your errors without plunker, even with supplied screenshots or anything else.Kotta
I have created plunker its working..But y not in my applicationLashonda
I removed dependency from moment.js, try again.Kotta
Yes.. I have a doubt.When converting to number format will there be any issue.Because when produceDate is inbetween from and to date in date format and when the same converted to number format produceDate will be smaller than from and to date..?whyLashonda
It is enough, sorry, that my answer was not useful for you.Kotta
M
1

Here is your required solution. I too used moment js, but took rather a simple approach by comparing the epoch times as per the data given by you.

<!DOCTYPE html>
<html>

<body>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-datepicker/2.1.19/angular-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-datepicker/2.1.19/angular-datepicker.min.css" rel="stylesheet" type="text/css" />

<div ng-app='app' ng-controller="MyController">        
<div>
fromDate: <datepicker date-format="dd/MM/yyyy"><input ng-model="from_date" type="text"/></datepicker>     
</div>            
<div>
toDate: <datepicker date-format="dd/MM/yyyy"><input ng-model="to_date" type="text"/></datepicker>       
</div>  
search:
<br/>
<input type='text' ng-model='search'/>
    <ul>
      <li ng-repeat="item in produceList | dateRange:from_date:to_date |filter:search">
        {{item | json}}
      </li>
    </ul>
</div>
<script>
angular.module('app', ['720kb.datepicker']).controller('MyController', function ($scope) {  
  var formatStr = 'DD/MM/YYYY';
    $scope.from_date = moment("2017-04-05").format(formatStr);
  $scope.to_date = moment("2017-04-29").format(formatStr);  
    $scope.produceList = [{
 	"itemName": "Mango",
 	"produceDate": 1493360722000,
 	"produceId": 90
 }, 
 {
 	"itemName": "Banana",
 	"produceDate": 1493290754000,
 	"produceId": 89
 }, 
 {
 	"itemName": "Grapes",
 	"lastDateForBid": 1493510400000,
 	"produceDate": 1493099760000,
 	"produceId": 83
 },
  {
 	"itemName": "Apple",
 	"produceDate": 1491808021000,
 	"produceId": 66
 },
 {
 	"itemName": "test1",
 	"produceDate": 1491805456000,
 	"produceId": 65
 },
 {
 	"itemName": "test2",
 	"produceDate": 1490615680000,
 	"produceId": 65
 },
 {
 	"itemName": "test3",
 	"produceDate": 1490615515000,
 	"produceId": 65
 },
 {
 	"itemName": "test4",
 	"produceDate": 1490611140000,
 	"produceId": 65
 },
 {
 	"itemName": "test5",
 	"produceDate": 1490352067000,
 	"produceId": 65
 },
  {
 	"itemName": "test6",
 	"produceDate": 1490271418000,
 	"produceId": 65
 },
  {
 	"itemName": "test7",
 	"produceDate": 1489828994000,
 	"produceId": 65
 }
 ]

 })

 .filter('dateRange', function() {
    var formatStr = 'DD/MM/YYYY';
    return function(produceList, fromDate, toDate) {    
      if(fromDate && toDate){
        var filtered = [];
        angular.forEach(produceList, function(items) {
          console.log('a',items.produceDate)
                              console.log(Date.parse(moment(fromDate, formatStr)))
            if (items.produceDate > Date.parse(moment(fromDate, formatStr)) && items.produceDate < Date.parse(moment(toDate, formatStr)))
                filtered.push(items);
        });
        return filtered;
      }
      else
        return produceList;
}})
</script>

</body>
</html>

Here is a Working DEMO

Marybethmaryellen answered 16/5, 2017 at 6:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.