Angular Datatables saveState not working

2.1k views Asked by At

When i click a specific entry from 2nd page of my datatable it redirects me to another page, and when i come back it redirects me to page 1. The issue here is i want to save the state and i want to go back to the page(Ex: 2) from where i was redirected.

.withOption('bStateSave',true)
    .withOption('stateSaveCallback', function (aoData,  oSettings) {
        console.log('performing save of settings');
        localStorage.setItem( 'DataTables_home', JSON.stringify(aoData)) ;
    })  
    .withOption('stateLoadCallback', function (oSettings) {
        console.log('performing load of settings');
        return JSON.parse( localStorage.getItem('DataTables_home') );
    });

Error:

 Unexpected token o in JSON at position 1
    at Object.parse (<anonymous>)
    at jQuery.fn.init.<anonymous> (app.js:14430)
    at _fnLoadState (jquery.dataTables.js:6308)
    at HTMLTableElement.<anonymous> (jquery.dataTables.js:1221)
    at Function.each (base.js:365)
    at jQuery.fn.init.each (base.js:137)
    at jQuery.fn.init.DataTable [as dataTable] (jquery.dataTables.js:869)
    at jQuery.fn.init.$.fn.DataTable (jquery.dataTables.js:15105)
    at Object.renderDataTable (angular-datatables.js:757)
    at Object.hideLoadingAndRenderDataTable (angular-datatables.js:773)

Cannot read property 'parentNode' of null
    at _Api.<anonymous> (jquery.dataTables.js:9213)
    at _Api.iterator (jquery.dataTables.js:6978)
    at _Api.<anonymous> (jquery.dataTables.js:9212)
    at _Api.destroy (jquery.dataTables.js:7141)
    at jQuery.fn.init.DataTable.fnDestroy (jquery.dataTables.js:412)
    at HTMLTableElement.<anonymous> (jquery.dataTables.js:923)
    at Function.each (base.js:365)
    at jQuery.fn.init.each (base.js:137)
    at jQuery.fn.init.DataTable [as dataTable] (jquery.dataTables.js:869)
    at jQuery.fn.init.$.fn.DataTable (jquery.dataTables.js:15105)

It would really help a lot if you could provide me with an example. Thank you.

The Versions I'm using angular version: v1 jquery version: 2.2.4 datatables version: 1.10.12 angular-datatables version: 0.5.5

1

There are 1 answers

0
Atul Girishkumar On BEST ANSWER

The issue is resolved using the following code:

<table id="example" datatable 
  dt-options="showCase.dtOptions"
  dt-columns="showCase.dtColumns">
</table>

vm.dtOptions = DTOptionsBuilder.fromSource('data.json')
  .withOption('stateSave', true)
  .withOption('stateSaveCallback', function(settings,data) {
    localStorage.setItem('DataTables_' + settings.sInstance, JSON.stringify(data));
  })
  .withOption('stateLoadCallback', function(settings) {
    return JSON.parse(localStorage.getItem('DataTables_' + settings.sInstance ))
  });