How to sort and filter ngTable date (milliseconds) data?

笑着哭i 提交于 2019-12-07 14:06:12

问题


I am pretty new to Angularjs need some help with sorting date in milliseconds in descending order as well as a filter for the table columns. I created a plunker here but when I key in some filter param I do not see any filtered data and the data is lost from table.

Please help me in sorting date column and doing a case insensitive filter search, below I am providing my code.

<table ng-table="tableParams" show-filter="true" class="table" >
  <tr ng-repeat="item in $data" height="10px">
    <td data-title="'Date'" filter="{ 'item[0]': 'date' }" sortable="'item[0]'">{{translate(item[0])}}</td>
    <td data-title="'Count'" filter="{ 'item[1]': 'text' }" sortable="'item[1]'">{{item[1]}}</td>
  </tr>
</table>

$scope.translate = function(value) {
    if (value == null || value == undefined)
        return value;
    var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
    var myDate = new Date( value );
    return myDate.getDate() + " " + monthNames[myDate.getMonth()] + " "+myDate.getFullYear();
}
$scope.tableParams = new ngTableParams({
    page: 1,            // show first page
    count: 10          // count per page        
}, {
    total: $scope.tasksRunDataForTable.length, // length of data
    getData: function($defer, params) {
        // use build-in angular filter
        var sortedData = params.sorting() ?
                            $filter('orderBy')($scope.tasksRunDataForTable, params.orderBy()) :
                            $scope.tasksRunDataForTable;
        var orderedData = params.filter() ?
               $filter('filter')(sortedData, params.filter()) :
               sortedData;
        params.total(orderedData.length); // set total for recalc pagination
        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
    }
});

Update

I am able to get filter work on count, but no luck with date and sorting on both columns. Updated plunker

<td data-title="'Count'" filter="{ '1': 'text' }" sortable="'1'">{{item[1]}}</td>

回答1:


Date Sorting

This is not an issue of the ngTable but how the underlying angular filter for 'OrderBy' works.

Just use valueOf()[0], valueOf()[1] respectively where 0 & 1 are the indexes for your inner array. Here is the html and there is no need to change your getData callback.

<table ng-table="tableParams" show-filter="true" class="table" >
    <tr ng-repeat="item in $data" height="10px">
        <td data-title="'Date'" filter="{ '0': 'text' }" sortable="valueOf()[0]">{{ item[0] | date: 'd MMM yyyy HH:mm' }}</td>
        <td data-title="'Count'" filter="{ '1': 'text' }" sortable="valueOf()[1]">{{ item[1] }}</td>
    </tr>
</table>

Please note that you don't need a translate for presenting your dates from milliseconds as this is supported by an other angular filter 'date'.

See also this somehow related post https://stackoverflow.com/a/15858739/61577

Date Filtering (from string)

In order to achieve filtering from date you need to use a custom "comperator" function as a third argument when filtering on the controller. Something like this will do the trick

var dateComperator = function(obj, text) {
   var valueAsText = obj + '';
    if (valueAsText.length == 13) { // must be milliseconds.
      valueAsText = $filter('date')(obj, 'd MMM yyyy HH:mm');
    } 
    return !text || (obj && valueAsText.toLowerCase().indexOf(text.toLowerCase()) > -1);
};

then on your controller getData callback:

    getData: function($defer, params) {
        // use build-in angular filter
        var sortedData = params.sorting() ?
                            $filter('orderBy')($scope.tasksRunDataForTable, params.orderBy()) :
                            $scope.tasksRunDataForTable;
        var filterInfo = params.filter();
        var comparer = (filterInfo && filterInfo['0']) ? dateComparer : undefined;
        $log.log(angular.toJson(filterInfo))
        var orderedData = filterInfo ?
               $filter('filter')(sortedData, filterInfo, comparer) :
               sortedData;
        params.total(orderedData.length); // set total for recalc pagination
        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
    }

UPDATE: updated the answer to tackle the filtering issue. UPDATE 2: Updated the answer to tackle when searching with both date and count.

here is the complete plunker http://plnkr.co/edit/D2n7MdAfugXpKeKOGosL?p=preview

Hope this helps.




回答2:


My solution:

        $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: STATIC_CONST.COUNT_PAGAING,         // count per page IMPORTANT 
        sorting: { Id: "desc" }

    }, {
        total: data.length, // length of data
        paginationMaxBlocks: 13,
        paginationMinBlocks: 2,
        getData: function ($defer, params) {

            var filters = angular.copy( params.filter() );
            //var filters = params.filter();
            var filteredData = data;

            //Custom filters:
            if (typeof filters['LastUpdateDate'] !== 'undefined') {
                filteredData = $filter('filterByUI')(filteredData, 'LastUpdateDate', filters['LastUpdateDate'], $filter('date'), ['dd.MM.yyyy']);
                delete filters['LastUpdateDate'];
            }

            //General filters:
            if (filters) {
                // use build-in angular filter
                filteredData = $filter('filter')(filteredData, filters);
            }


            //if (filters.FromDate) {
            //    filteredData = $filter('filterDates')(data, filters.FromDate);
            //}

            var orderedData = params.sorting() ?
              $filter('orderBy')(filteredData, params.orderBy()) :
              filteredData;


            params.total(orderedData.length); // set total for recalc pagination
            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        }
    });

Layout.html:

<table ng-table="tableParams" show-filter="true" class="table" >
<tr ng-repeat="item in $data" height="10px">
    <td data-title="'Date'" filter="{ 'LastUpdateDate': 'text' }" sortable="valueOf()[0]">{{ item[0] | date: 'd MMM yyyy HH:mm' }}</td>
    <td data-title="'Count'" filter="{ '1': 'text' }" sortable="valueOf()[1]">{{ item[1] }}</td>
</tr>

\apps\app.module.js:

app.filter("filterByUI", function () {

    debugger;

    return function (arrayData, dateKey, dateValue, filterFunction, filterFunctionParams) {
        var returnarr = [];
        returnarr = arrayData.filter(function (element) {
            var evalCode = "filterFunction( element." +dateKey;
            filterFunctionParams.forEach(function (element, index, array) {
                evalCode += ", filterFunctionParams["+index+"]";
            });
            evalCode += ")";

            try{
                var dudi86 = eval(evalCode);

                if(typeof dudi86 === 'number') {
                    dudi86 = dudi86.toString();
                }

                if(typeof dudi86 === 'string') {
                    return dudi86.toLowerCase().indexOf( dateValue.toString().toLowerCase() ) > -1;
                }

                if( Array.isArray(dudi86) ) {
                    if( Array.isArray(dateValue) ) {
                        return dateValue.every( function(val) { return  dudi86.indexOf(val) >= 0; } );
                    }

                    if(typeof dateValue === 'string' || typeof dateValue === 'number') {
                        //TODO: Consider this case:
                        return dudi86.indexOf( dateValue.toString().toLowerCase() ) > -1;
                    }
                }



            }catch(e){
                console.log("app.filterByUI: Error on evaluating: " +evalCode);
            }


            return false;

        });

        return returnarr;

    }
});


来源:https://stackoverflow.com/questions/27243106/how-to-sort-and-filter-ngtable-date-milliseconds-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!