Cease the ngTable getData function for ngTableDynamic in order to retrieve data while sorting

The ngTable documentation lacks adequate information and sample codes, making it difficult to follow. Despite this, I was able to create the following code to dynamically fetch and display a table from the server. However, when I try to sort by clicking on the table header, the getData function (and consequently $http) is triggered again. As a result, after clicking, the column is not sorted, but the displayed data duplicates itself horizontally (for example, initially displaying columns [id, name], then becoming [id, name, id, name] after sorting).

<!DOCTYPE html>
<html>
<head lang="en">
  <title><%= title %></title>
  <meta charset="utf-8">
  <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
  <script type="text/javascript" src="bower_components/ng-table/ng-table.min.js"></script>
  <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />
  <link rel="stylesheet" href="bower_components/ng-table/ng-table.min.css" />
  <script>
    (function () {
      'use strict';
      let app = angular.module('myApp', ['ngTable']);
      app.controller('demoCtrl', ['$http', 'NgTableParams', function ($http, NgTableParams) {
        let ctrl = this;
        ctrl.cols = [];
        ctrl.rows = [];
        ctrl.tableParams = new NgTableParams({}, {
          getData: function (params) {
            ctrl.xhr = $http({
              method: 'GET',
              url: '/ng-table-demo/test_data',
            }).then(function (rsp) {
              let cols = Object.keys(rsp.data[0]);
              for(let i = 0; i < cols.length; i++) {
                ctrl.cols.push({field: cols[i], title: cols[i], sortable: cols[i], show: true});
              }
              ctrl.rows = rsp.data;
              return ctrl.rows;
            }, function (rsp) {
              console.log('http failed.');
            });
            return ctrl.xhr;
          }});
        }]);
      })();

    (function () {
      "use strict";
      angular.module("myApp").run(configureDefaults);
      configureDefaults.$inject = ["ngTableDefaults"];
      function configureDefaults(ngTableDefaults) {
        ngTableDefaults.params.count = 5;
        ngTableDefaults.settings.counts = [];
      }})();
  </script>
</head>
<body>
  <div ng-app="myApp" ng-controller="demoCtrl as ctrl" class="container-fluid">
    <h2>ng-table-demo</h2>
    <table ng-table-dynamic="ctrl.tableParams with ctrl.cols" class="table table-condensed table-bordered table-striped">
      <tr ng-repeat="row in $data">
        <td ng-repeat="col in $columns">{{row[col.field]}}</td>
      </tr>
    </table>
  </div>
</body>
</html>

I attempted to wrap the ctrl.xhr block with the following code snippet, which helped prevent duplication but did not resolve the issue with sorting.

if(ctrl.xhr === undefined) {
  ctrl.xhr = $http...;
}
return ctrl.xhr;

What mistake(s) have I made?

Answer №1

A different approach is to stop using getData and instead assign the dataset property once the xhr request succeeds. See the code snippet below for a working example.

(function () {
  'use strict';
  let app = angular.module('myApp', ['ngTable']);
  app.controller('demoCtrl', ['$http', 'NgTableParams', function ($http, NgTableParams) {
    let ctrl = this;
    ctrl.cols = [];
    $http({
      method: 'GET',
      url: '/ng-table-demo/test_data',
    }).then(function (rsp) {
      let cols = Object.keys(rsp.data[0]);
      for (let i = 0; i < cols.length; i++) {
        ctrl.cols.push({
          field: cols[i],
          title: cols[i],
          sortable: cols[i],
          show: true
        });
      }
      ctrl.tableParams = new NgTableParams({}, {
        dataset: rsp.data
      });
    }, function (rsp) {
      console.log('http failed.');
    });
  }]);
})();

I'm still unsure about the functionality of getData.

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

The code within the then() promise resolver function will always execute, regardless of whether the promise succeeds or

After clicking a button, I trigger a vuex action which returns an axios promise from the store. In my component, I only want to reset form fields when the action is successful. However, currently the form fields are always reset, even if the promise fails. ...

Utilize conditional styling in Vue using CSS

I am having difficulty implementing a conditional Vue statement to change the CSS style based on the text value. Despite trying other tutorials, I have had no success due to my limited experience with Vue. For example, if I want the class to be "is-succes ...

Is it possible to create an HTML form to edit XML data?

I'm currently working on developing a JavaScript plugin that will allow users to easily edit XML files. The idea is to take an XML string representing an object, generate an HTML form dynamically for editing the values, and then save the changes back ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...

Retrieving and setting data in ReactJS

Currently utilizing Reactjs in tandem with MongoDB. Once a user makes a selection in Reactjs, that value is then sent over to MongoDB. addTodo(event) { event.preventDefault(); var roomID = this.state.selectedRoomID; console.log(Ro ...

I'm puzzled as to why my createDoorMethod is returning a string value instead of a number, even though I am passing it a number. Can someone help me

Currently enrolled in a web development course, I am diving into the world of Angular 2 and TypeScript. Despite following along with the video tutorial and using the same code, my implementation is not working as expected, leaving me puzzled. Here is the ...

Show the total of a JavaScript calculation in a designated input box

Is there a way to show the total sum of this calculation in an input field? function calculateSum1() { var sum = 0; //loop through each textbox and add their values $("input.miles").each(function() { //only add if the value is a number ...

The issue of unselection not functioning properly for multiple items when using both selectable and draggable features

i need the unselection of list items to be as smooth as selectable() but without draggable() My desired outcome is similar to the following gif showcasing combined selectable and draggable functionality: https://i.stack.imgur.com/3GjTD.gif here's t ...

What is the process for transferring `Parentobject1` to `childobject2` and `childobject3` in Three.js?

I have created two objects doubleSquare and doubleSquare1. I was expecting the output to be Double Line Square Object, but I have tried two different formats and have not achieved the desired output. Can someone please provide me with a solution? I have lo ...

Trouble with Global Variable Allocation in jQuery Ajax

I've got a script that includes a jQuery Ajax call: <script type="text/javascript"> $(document).ready(function() { var timer; $.ajax({ type: 'POST', url: 'closettime.php', success: function( res ) ...

Coloring weeks in fullcalendar's two-shift calendar

Can FullCalendar create a calendar with alternating colors for odd and even weeks? Visit the FullCalendar demos here For example, see image below: https://i.sstatic.net/D5qza.png ...

Issues with jquery gui elements in Chrome extension being unresponsive

Using chrome extensions and jquery to create a customized GUI, but running into issues with displaying the jquery elements on the HTML page. Can anyone spot what might be the problem? manifest.json: { "name": "my extension", "description": "my first ...

Modifying the background image of div elements with JQuery in a loop function is ineffective when using Google Chrome

I am facing an issue in my application where I have a for loop to change the background image of two divs. The code snippet is as follows: for (var i = 0; i < length; i++) { $("div_" + (i + 1)).css("background-image", "../imageFile.png"); ...

The alert box in Javascript appears before the execution of the statement preceding it

I am encountering a peculiar issue, which is not unexpected considering my limited experience with JavaScript. I am currently working on developing a basic high-low card game where two cards are drawn and the highest card wins. Below you can find the code ...

What is causing the error message of "prop id does not match the rendered server output" to appear on my screen?

https://i.stack.imgur.com/VOLDT.png I've been working on a nextjs redux project and I keep running into this error whenever I refresh my page. Despite searching for a solution, I haven't been able to resolve it. The official next js blog suggest ...

Get image data from Next.JS API and show it in the web browser

I am looking to utilize my own next.js endpoints to request an image that I can then embed into my website. Currently, the issue I am facing is that the image seems to be immediately downloaded and does not display in the browser window. import type { Next ...

What is the best way to identify the specific row and column that was clicked within a jQuery datatable

Scenario: When a user clicks on a cell in a datatable, a specific action should be triggered based on the row and column of that cell. How can I ensure that the user does not click on a certain column? If they do not click on that column, then I want to r ...

Error alert: The system could not locate Google when trying to drop pins

Every time I attempt to place pins on the map, I encounter the "google is not defined" error. The map itself displays without any issues until I add the lines following the initMap() function. I have come across similar posts but none of the suggested so ...

Can a webpage be redirected to another page while passing along the id from the original page?

https://i.sstatic.net/3LhYJ.png I have a page that displays shop names and addresses along with an edit function in views.py: def update_shop(request, id): context = {} # * fetch the object related to passed id obj_shop = get_object_or_404(VideoL ...

JavaScript and jQuery syntax are essential for web development. Understanding how

I've been searching everywhere but couldn't find syntax similar to this: var mz = jQuery.noConflict(); mz('#zoom01, .cloud-zoom-gallery').CloudZoom(); This basically means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery') ...