Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

angularjs - ng-repeat filtering data by date range

I'm trying to filter a list that contains a timestamp by typing a range of dates

for example:

JSFIDDLE

html

<div ng-app="tst">
    <div ng-controller="MyController">
        <table>
            <tr>
                <td>From:
                    <input ng-model="query.date1" type="text" placeholder="" />
                </td>
                <td>To:
                    <input ng-model="query.date2" type="text" placeholder="" />
                </td>
            </tr>

            <tr ng-repeat="order in orders |filter:query">
                <td>{{order.date1 * 1000 | date:'dd-MM-yyyy'}}</td>
                <td>{{order.date2 * 1000 | date:'dd-MM-yyyy'}}</td>
            </tr>
        </table>
    </div>
</div>

javascript

var nameSpace = angular.module('tst',[]);

nameSpace.controller('MyController', function MyController($scope) {
  $scope.orders = [
  {
    "date1":"1306487800",
    "date2":"1406587800"
  },
  {
    "date1":"1196487800",
    "date2":"1406597800"
  }]
});

i want to be able to fill the "From" field with the value : 27-05-2010

and the "To" field the value of : 29-07-2015

and get only the records that are in this range.

(the first record in the example).

Thanks allot Avi

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create a custom filter to achieve this aim.

JSFIDDLE

html

<input ng-model="dateFrom" type="text"/>
<input ng-model="dateTo" type="text"/>
<tr ng-repeat="order in orders | myfilter:dateFrom:dateTo">
  <td>{{order.date1 * 1000 | date:'dd-MM-yyyy'}}</td>
  <td>{{order.date2 * 1000 | date:'dd-MM-yyyy'}}</td>
</tr>

javascript

function parseDate(input) {
  var parts = input.split('-');
  return new Date(parts[2], parts[1]-1, parts[0]); 
}

nameSpace.filter("myfilter", 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 tf = new Date(items[i].date1 * 1000),
                tt = new Date(items[i].date2 * 1000);
            if (tf > df && tt < dt)  {
                result.push(items[i]);
            }
        }            
        return result;
  };
});

also, i changed the timestamp data type from string to numbres.

  $scope.orders = [
  {
    "date1": 1306487800,
    "date2": 1406587800
  },
  {
    "date1": 1196487800,
    "date2": 1406597800
  }]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...