数据过滤器“从,到”Angular

时间:2016-12-28 18:54:33

标签: javascript angularjs json filter

这是我的json:

[
    {
        "name": "2QQQJohnQQQ11_12_1998",
        "age" : "18"
    },
    {
        "name": "1QQQEvaQQQ05_11_1989",
        "age" : "21"
    },
    {
        "name": "4QQQCasperQQQ12_06_1994",
        "age" : "13"
    },
    {
        "name": "3QQQBeanQQQ30_12_1996",
        "age" : "6"
    }]

我的Html:

 <thead>
                    <tr>
                        <th class="text-center">type</th>
                        <th class="text-center">name</th>
                        <th class="text-center">date</th>
                        <th class="text-center">age</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="name in namesplit | filter:dateFilterFunction | orderBy:'time'">
                        <td>{{name.type}}</td>
                        <td>{{name.name}}</td>
                        <td>{{name.time | date}}</td>
                        <td>{{name.age}}</td>
                    </tr>
                </tbody>

我的javascript文件:

var app = angular.module('app', []);
    app.service('service', function($http, $q){
        var deferred = $q.defer();

        $http.get("datesss.json").then(function(data){
            deferred.resolve(data);
        });

        this.getNames = function(){
            return deferred.promise;
        }
    });
    app.controller('secondCtrl', function($scope, service){
        var promise = service.getNames();
        promise.then(function(data){
            $scope.names = data.data;
            $scope.namesplit = $scope.names;
            $scope.namesplit.map(function(item) {
                item.type = item.name.split('QQQ')[0];
                item.data = item.name.split('QQQ')[2].split('_');
                item.name = item.name.split('QQQ')[1];
                item.time = new Date(parseInt(item.data[2],10),parseInt(item.data[1],10)-1,parseInt(item.data[0],10));
        });
    });
});

我正在做一个表,我尝试做的是过滤“from,to”过滤数据(name.time)。我在HTML中的代码:

<input type="date" ng-model="dateFilter.from" class="form-control" />
<input type="date" ng-model="dateFilter.to" class="form-control" />

我在控制器中的代码:

$scope.dateFilter={};
                $scope.dateFilterFunction= function(name){
                    return (name.time>$scope.dateFilter.from && name.time<$scope.dateFilter.to);
        }

它不起作用。有人帮忙吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

试试这个date filter

我们需要按如下方式声明过滤器: -

.filter('dateFilterFunction',function(){
  return function(data, from, to) {
    if (!from && !to) return data;
    var newData = [];
    angular.forEach(data, function(item){
      if (item.time >= from && item.time <= to) {
           newData.push(item);  
      }

    });
    return newData;
  };
});