What is the best way to trigger a refresh callback on Angular datatable pagination after updating the data

I've successfully set up my angular datatable configuration. Here's what it looks like:

  vm.dtOptions = DTOptionsBuilder.newOptions().
            withPaginationType('full_numbers').
            //withOption('ajax', {
            //    url: 'rest/get/'+entityName,
            //    type: 'GET'
            //}).
            withOption('serverSide', true).
            withOption('ajax', function(data, callback, settings) {
                    EntityManager.get({entity:entityName,action:'get',start:data.start,length:data.length}).$promise.then(function(response) {
                    console.log('response');
                    console.log(response);
                    vm.objectList = response.data;

                    callback({
                        recordsTotal:    response.recordsTotal,
                        recordsFiltered: response.recordsFiltered,
                        data: response.data
                    });

                });
            }).
            withDataProp('data').
            withOption('processing', true).
            withOption('bFilter', false).
            withOption('bSort', false).
            withOption("aaSorting", []).
            withDisplayLength(10);

However, I'm encountering an issue with the filtering function. It updates the data and recordsTotal, but the pagination doesn't get re-rendered - specifically, the last button number isn't modified as expected. Is there a way to trigger the following code block from the controller?

 callback({
      recordsTotal:    response.recordsTotal,
      recordsFiltered: response.recordsFiltered,
      data: response.data
 });

Which objects and methods are responsible for updating the pagination in this context?

Answer №1

After much searching, I have finally discovered the solution. Firstly, make sure to include dt-instance in the markup:

 <div ng-controller="DataTableController as listTable" ng-init="init('informsystem')">
   <table datatable="" dt-options="listTable.dtOptions" dt-instance="listTable.dtInstance" class="row-border hover">

In the controller, declare the dtInstance variable and ensure it is initialized. Move all ajax callback logic into a separate function and pass it in dtoptions and filter:

 var vm = this;
 vm.dtInstance = {}; //MAKE SURE TO INITIATE IT! REMEMBER vm.(this) before varName

        var ajaxCallback = function(data, callback, settings) {
            $scope.filter.start = data.start;
            $scope.filter.length = data.length;
            console.log($scope.filter);
            EntityManager.get($scope.filter).$promise.then(function(response) {
                console.log('response');
                console.log(response);
                vm.objectList = response.data;

                callback({
                    recordsTotal:    response.recordsTotal,
                    recordsFiltered: response.recordsFiltered,
                    data: response.data
                });

            });
        };

Utilize ajaxCallback in the config:

   ....withOption('ajax', ajaxCallback ).....

In doFilter/doSearch:

  $scope.doFilter = function () {
            console.log(vm.dtInstance);
            vm.dtInstance.changeData(ajaxCallback);
        };

$scope.filter is populated in init with common params of $resource, while start and length (offset) are added in the callback. The filter also contains values from html inputs bound via ng-model.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on bringing data from a php file into a javascript variable

I'm faced with a challenge where I need to extract data from a MySQL database using a PHP file and then store that data in a JavaScript array for plotting purposes with jQuery's flot library. Has anyone encountered a similar situation and found a ...

Executing API call utilizing the Request module within a node.js application

In my node.js app, I have a request call that looks like this: request({ url:chanURL, qs:chanProperties}, function(err, response, body) { if(err) { console.log(err); return; } body = JSON.parse(body); (function (body) { Objec ...

The potential issue of undefined objects in TypeScript when utilizing computed properties in Vue3

https://i.sstatic.net/I5ZVO.png I've attempted adding a ? after each word and also experimented with the following code: const totalNameLenght = computed(() => { if (userFirstnameLenght.value && userLastnameLenght.value){ ret ...

The problem with setting headers in Node Express MySQL: Error message indicating headers cannot be set after they have been sent

I'm currently working on a project using Node.js, Express.js, and a MySQL database. I have posts stored in the database that I want to display using the Pug.js view engine. I've managed to connect to the database and render the home route success ...

Storing various text inputs in a MySQL database

Could anyone please assist me with fixing an issue I'm having with inserting data into a database from the form provided below? Unfortunately, I am unable to get it to work as expected. Here is the complete form: <html> <head> <m ...

Whenever I attempt to use for or while loops in my application, it consistently crashes

I've recently started learning reactjs and I'm working on a simple app. I created a decrement button that should only work if the item count is greater than or equal to zero. However, when I tried using while and for loops in my code, my app cras ...

Link property can be added to a bindpopup polygon in Leaflet to have it open in a new tab when clicked

Is it possible to include a hyperlink in popup content on Leaflet, similar to this example? function onEachFeature(feature, layer) { idLoDat = feature.properties.IDLo; layer.bindPopup("Company name: " + feature.properties.TenCty + " ...

Conceal and Reveal every marker on the map

Creating a map using angular to display data on the web page and Google Map is my current project. This is my first major project utilizing Angular, and I have nearly achieved the functionality as planned. I am eager to enhance the site with more user-fri ...

Express 4 Alert: Headers cannot be modified once they have been sent

I recently upgraded to version 4 of Express while setting up a basic chat system. However, I encountered an error message that says: info - socket.io started Express server listening on port 3000 GET / 304 790.443 ms - - Error: Can't set headers ...

Discover the effective method in Angular to display a solitary password validation message while dealing with numerous ones

Here is the pattern we use to validate input fields: The length of the input field should be between 6 and 15 characters. It should contain at least one lowercase letter (a-z). It should contain at least one uppercase letter (A-Z). It should contain at le ...

Creating separate UI-views using ui-router within a single module

Can two independent ui-views be created using ui-router for a single module? The objective is to have the ui-views "know" where to display the current state, essentially creating a form of redirection. https://i.sstatic.net/OTNNL.png ...

Guide to resetting all ReactiveVars to false in Meteor JS

I am currently working on a recipe template where I am using {{#each recipes}} to render the recipes. I have implemented ReactiveVar to toggle the edit form of each recipe from hide to show. Everything is functioning correctly, but I want to ensure that ...

Overlap one element entirely with another

Currently, I am working on a way for an element called overlayElement to completely cover another element known as originalElement. The overlayElement is an iFrame, but that detail may not be significant in this scenario. My goal is to ensure that the over ...

Is there a way to simulate the parameters of a method callback from an external dependency in Nodejs

Imagine a scenario where I have the following structure: lib/modules/module1.js var m2 = require('module2'); module.exports = function(){ return { // ... get: function(cb){ m2.someMethod(params, function(error, ...

"Unleashing the power of perpetual testing: A guide to seamlessly integrating Protractor with SauceL

My website has a web server running protractor tests, and I am looking to set up continuous testing with Saucelabs. According to Saucelabs, all I need to do is add my Saucelabs username and key to the conf.js file of Protractor. Would using cron or anothe ...

Store and retrieve user input using JavaScript or JSON

Can someone please assist me in finding a solution to this problem? I have 3 input fields where users can type in their answers. There is also a "SAVE" button that allows users to download their input values into a file.txt. Additionally, there is a "choos ...

Using JSON objects effectively in MVC4, including parsing them seamlessly!

I am struggling with understanding how to effectively utilize JSON objects within MVC and the correct way to pass them from Controller, to View, to Jscript. I am also unsure if I am correctly parsing the JSON objects at the appropriate places... Within m ...

How can I extract only certain keys from a large JavaScript object while keeping the code concise?

Simply put, I aim to streamline objects by discarding unnecessary keys. Imagine a scenario where a third party API sends back JSON data with numerous attributes that hold no importance to you. obj = { name: ..., id: ..., description: ..., blah: .. ...

Problem arises with table nth-child selector following the addition of grid-gap

Our current table looks like this: https://i.sstatic.net/eUyBB.png The first row has a background color and the second row is white - which is correct. Now I would like to align the attributes to the right. I added the following code to the table: .table ...

Encountering an issue with Angular routing: Cross-origin requests are restricted to specific protocol schemes, such as HTTP

I encountered an error while working on angular routing. Below is my HTML code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <script src= ...