Retrieving JSON data using AJAX while incorporating NgTable settings

I'm currently facing an issue with sorting and filtering data in ngTables using an AJAX call. Although I have managed to display the data using ng-repeat, the sorting functions do not work as expected. After referencing this example http://plnkr.co/edit/zuzcma?p=info, I was able to make it function with a mock.js file. However, I am now working with a file hosted on my webserver, and I can't seem to get it to work.

I believe the solution is straightforward, and I would appreciate any assistance. Below, I have included my markup to provide insight into what my controller and HTML files look like. Thank you all for your help, and feel free to ask for more information if needed!

Below are some API links that I am referring to:

HTML:

<div ng-controller="myController">
  <table ng-table="tableParams" show-filter="true" class="table table-condensed">
    <tr ng-repeat="user in data">
      <td data-title="foo" sortable="foo">{{user.foo}}</td>
      <td data-title="bar" sortable="bar">{{user.bar}}</td>
    </tr>
  </table>
</div>

Controller:

var app = angular.module('app', ['ngTable']);

app.controller('myController', function($scope, $http, $filter, ngTableParams) {

 $http.get('http://jsondata.com/myjson.json')
  .success(function(data, status) {
    $scope.data = data;
  });

$scope.tableParams = new ngTableParams({
    page: 1,            // show first page
    count: 10,          // count per page
    sorting: {
        foo: 'asc'     // initial sorting
    }
}, {
    total: data.length, // length of data
    getData: function($defer, params) {
        var orderedData = params.sorting() ?
                            $filter('orderBy')(data, params.orderBy()) :
                            data;

        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
    }
  });
});

Answer №1

Your issue arises from using the local variable data within your ngTableParams while also being outside the scope of the success function.

To resolve this, consider updating your code as follows:

var app = angular.module('app', ['ngTable']);

app.controller('myController', function($scope, $http, $filter, ngTableParams) {

 $http.get('http://jsondata.com/myjson.json')
  .success(function(data, status) {
    $scope.data = data;

    $scope.tableParams = new ngTableParams({
        page: 1,            
        count: 10,          
        sorting: {
            foo: 'asc'     
        }
    }, {
        total: $scope.data.length, 
        getData: function($defer, params) {
           
            var orderedData = params.sorting() ?
                                $filter('orderBy')($scope.data, params.orderBy()) :
                                $scope.data;

            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        }
      });
  });


});

Note the change from data to $scope.data within ngTableParams.

Additionally, if you only place your ngTableParams inside the success function, it should work without changing data to $scope.data. However, updating the variables will provide more flexibility when utilizing functions like reload() on your table.

Answer №2

Ensure that $defer is resolved within the getData function, after the completion of the ajax call. In this specific scenario where the ajax call is embedded within the getData function:

var app = angular.module('app', ['ngTable']);

app.controller('myController', function($scope, $http, $filter, ngTableParams) {

$scope.tableParams = new ngTableParams({
    page: 1,
    count: 10,
    sorting: {
        foo: 'asc'
    }
}, {
    total: data.length,
    getData: function($defer, params) {
        $http.get('http://jsondata.com/myjson.json')
           .success(function(data, status) {

               // utilize angular filter
               var orderedData = params.sorting() ?
                   $filter('orderBy')(data, params.orderBy()) :
                   data;

               $defer.resolve(orderedData.slice((params.page() - 1) * params.count(),  params.page() * params.count()));
            });
        }
    });
});

Answer №3

To start, don't forget to surround your sortable attribute with quotes:

<td data-title="foo" sortable="'foo'">{{user.foo}}</td>

Make sure you have an expression in there for ngTable to work correctly.

Next, double check the version of ngTable you are using. If it's 0.3.2, take a look at this issue on ngTable's GitHub page: https://github.com/esvit/ng-table/issues/204

Best of luck!

Answer №4

<tr ng-repeat="person in $info">
      <td data-title="name" sortable="name">{{person.name}}</td>
      <td data-title="age" sortable="age">{{person.age}}</td>
</tr>

Accessing data directly in your JavaScript code without setting it to a $scope variable like $scope.info = info worked perfectly for me as well.

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

Issue with Node.js OAuth authentication

As someone new to Node.js and specifically OAuth, I have been exploring the use of Google APIs with Node.js. So far, here is what I've accomplished: var fs = require('fs'); var readline = require('readline'); var google = require( ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Troubleshooting overlap problem between Skrollr and SlickNav

I successfully implemented Skrollr to fix images, similar to this example: Additionally, I am utilizing Slicknav for the menu functionality. However, I encountered an issue where the menu opens behind the fixed "parallax" image. Despite trying various ap ...

Utilizing JavaScript to dynamically alter an image based on selected dropdown option

I am currently facing an issue with my code where the selected image is not changing when I choose an option from the dropdown list. There are a total of 5 images, but for some reason, they are not displaying correctly. Here is the snippet of my code; < ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

Managing date fields retrieved from a REST Api in AngularJS

One of the challenges I'm facing involves a REST API that sends back JSON data with dates formatted in ISO-8601 style: yyyy-MM-ddTHH:mm:ss: { id: 4 version: 3 code: "ADSFASDF" definition: "asdflkj" type: "CONTAINER" value: "12 ...

Failure to send serialized data via AJAX to the specified URL

After executing the SUCCESS function, I have confirmed that my values are accurate: serviceID=123&acceptAgreement=on The acceptAgreement field is an input checkbox. Despite this, the DB file does not show any updates. To troubleshoot, I attempted to ...

What is preventing us from receiving JSON as the expected response?

Navigate to the following URL in your web browser: https://hnx.vn/en-gb/cophieu-etfs/chung-khoan-ny.html, then click on page 2. You will notice that the response content is in JSON format. https://i.sstatic.net/0iPSo.png To retrieve the JSON, I created a ...

Changing the style of opening curly braces in JavaScript code styling

I have a piece of JavaScript code written for Vue that I would like to discuss. It is common practice in the JavaScript world to place the opening curly brace at the end of a line of code. <script> export default { name: 'newUser', data ...

Incorporate personalized buttons into the header navigation for each view using VueJS

In my VueJS project, I attempted to include custom buttons in the sub navigation menu which could be customized for each view. Initially, I tried adding a simple property to the main data element, but that didn't yield the desired results. Then, I cam ...

The packery's overlapping issue arises when using the layout method to add HTML elements through AJAX, causing it to malfunction

This Example is not functioning The link above illustrates the issue I am facing. After adding text in a span using ajax, the divs started to overlap. However, when adding text without using ajax, the layout method worked properly. Example works fine wit ...

Add a custom Leaflet JS control button with personalized text and hover functionality

I successfully completed a control-button-leaflet tutorial and it worked for me. Now I have some additional requirements: Show some text when hovering over the button (similar to the zoom buttons) Change the button's color when hovering over it Abil ...

Looking for a JavaScript regex pattern that matches strings starting with the letter "p" and containing at least

I have recently started learning about JavaScript regular expressions. I attempted the following expression for a string starting with the letter "p" followed by digits: p1749350502 The letter "p" is constant and the remaining digits are variable. Howeve ...

Dynamic content display using AJAX

Having already tried to find a solution through Google with no success, I am at a loss. I have articles where a paragraph is initially displayed, followed by a "read more" link which reveals more content using JavaScript. However, this approach may slow do ...

Issues encountered with AngularJs filter search functionality

Why am I having trouble adapting this search filter from here? This is what my code looks like: controllers.js angular.module('starter.controllers', ['starter.services']) .controller('AppCtrl', function($scope, $ionicModal ...

Dealing with cross-origin AJAX posting in Node.js处理Node.js中的

My app.js contains the following handler for POST requests: app.all('/', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.opt ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

The OrderBy feature may not apply to the initial items being displayed in an ng-repeat loop

Curiously, when attempting to sort by name on an object array, the first 10 or so objects appear random before the orderBy function works correctly. Any suggestions on how to address this issue? Appreciate any assistance! ...

Utilize Ajax, jQuery, and Java to handle reading and writing text files efficiently

I need to handle a large number of text files on the server side, both reading and writing. Can someone provide guidance on how to utilize Ajax and Java for this task? I have some knowledge about these technologies, but I am seeking advice on how to actua ...