6

We have a Web form using Angular DataTables (DataTables 1.10.10 / angular-datatables - v0.5.3). We are feeding the data with a JSON coming from the backend. The table is configured with paging, and data feeding the table is reloaded manually every 10 secs. This is all working fine, when I select a different page from 1st one and the table get refreshed then paging is reset. I tried the different params of the draw(https://datatables.net/reference/api/draw()) method but did not make any difference.. Many thanks in advance!!

My HTML table:

<table datatable="ng" id="datatable1" dt-options="dtOptions" dt-column-defs="dtColumnDefs" class="table table-striped table-hover" dt-instance="dtInstance">

<tr ng-repeat="session in data.serverData[data.selectedAgent]" class="gradeX">

This is our controller:

App.controller("ReportAgentSessionsListController", [
"$scope", "$http", "sessionsListData", "$timeout", "DTOptionsBuilder", "DTColumnDefBuilder", function ($scope, $http, sessionsListData, $timeout, DTOptionsBuilder, DTColumnDefBuilder, DTInstances) {

$scope.dtOptions = DTOptionsBuilder.newOptions().withPaginationType("simple_numbers").withDisplayLength(25).withOption("retrieve", true).withOption('order', [0, 'desc']);
 $scope.dtColumnDefs = [
        DTColumnDefBuilder.newColumnDef(0),
        DTColumnDefBuilder.newColumnDef(1),
        DTColumnDefBuilder.newColumnDef(2),
        DTColumnDefBuilder.newColumnDef(3).notSortable(),
    ];

    // Get original request params
    $scope.dateData = JSON.parse(sessionsListData.config.data);

    var timer;  // used for auto-refresh
    var vm = this;
    $scope.cduInterval = 1000;
    $scope.counter = 0;
    $scope.dtInstance = {};
    $scope.data = {};
    $scope.data.serverData = [];

    var formatServerData = function(serverData) {

        $scope.agentsList = Object.keys(serverData);
        // If no agent has been selected
        if (!$scope.data.selectedAgent) {
            $scope.data.selectedAgent = $scope.agentsList[0];
        }
        // Format data
        for (var key in serverData) {
            if (serverData.hasOwnProperty(key)) {
                for (var i = 0; i < serverData[key].length; i++) {
                    var data = serverData[key][i];
                    data.waitTime = numeral(data.waitTime).format("00:00:00");
                    data.handleTime = numeral(data.handleTime).format("00:00:00");
                    data.revenue = numeral(data.revenue).format("$0,0.00");
                }
            }
        }
        $scope.data.serverData = serverData;
        // This does not do anything apparently
        if ($scope.dtInstance.DataTable) {
            $scope.dtInstance.DataTable.draw('full-hold');
        }
    };

    var scheduleTimeout = function () {
        var getFreshDataInterval = 1000;
        timer = $timeout(getFreshData, getFreshDataInterval);
    };

    // Request a new set of data from the server
    var getFreshData = function () {
        if ($scope.counter++ % 10 == 0) {   // Requests to server will be done every 10th request (10 secs)

            var response = $http({
                abp: true,
                url: abp.appPath + "Report/GetTeamSessionsByTimeInterval",
                method: "POST",
                data: sessionsListData.config.data
            }).then(function (response) {
                formatServerData(response.data);
                if (timer) {
                    scheduleTimeout();
                }
            });
        }
        else {
            if (timer) {
                scheduleTimeout();
            }
        }
    };

    // Is currentdate between the date ranges being displayed
    var isTodayInRage = function (currentdate) {
        ..
    }

    formatServerData(sessionsListData.data);

    if (isTodayInRage(userCurrentDate)) {
        // Date range includes Today (local time)
        scheduleTimeout();
    }

    $scope.selectAgent = function(agent) {
        $scope.data.selectedAgent = agent;
    };

    $scope.$on("$destroy", function () {
        if (timer) {
            $timeout.cancel(timer);
        }
    });
}]);

2 Answers 2

12

Enable or disable state saving. When enabled aDataTables will store state information such as pagination position, display length, filtering and sorting. When the end user reloads the page the table's state will be altered to match what they had previously set up.

use==> .withOption('stateSave', false) //or true as the case

Example

$scope.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('stateSave', false)
        .withPaginationType("simple_numbers")
        .withDisplayLength(25)
        .withOption("retrieve", true)
        .withOption('order', [0, 'desc']);

to learn more read the documentation stateSave

https://datatables.net/reference/option/stateSave

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

Comments

5

You can get the current page through the dtInstance

var page = $scope.dtInstance.DataTable.page()

and then redraw but stay on the current page number by

$scope.dtInstance.DataTable.page(page).draw(false)

Obviously I cannot replicate your code / scenario 1:1, but I would retrieve the current page as first thing in formatServerData()

var formatServerData = function(serverData) {
   var page = $scope.dtInstance.DataTable.page()
   ...

and after formatting of serverData

if ($scope.dtInstance.DataTable) {
   $timeout(function() {
      $scope.dtInstance.DataTable.page(page).draw(false)
   })
}

3 Comments

Many thanks David. I am able to get the current page, but when I try to redraw using it at the end of formatServerData() it does not work. The page is reset to the 1st one..
@JoseParra, sry for the long delay. I believe serverData is rendered out with ng-repeat? You might have a race issue here, try move $scope.dtInstance.DataTable.page(page).draw(false) into a $timeout (see update) so the setting of the page is done in the next $digest.
David, many thanks for your help. Yes I am using a ng-repeat. Unfortunately, it did not work. It is like the table gets fully redrawn after formatServerData(). Something odd is that any change to the sort order doesn't get reset on refresh.

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.