The functionality of ng-table appears to be compromised when working with JSON data

Currently, I am facing an issue while using a JSON file to populate data in my Angular ng-table. Even though the JSON data is being displayed in a regular table format, certain functionalities of ng-table like pagination and view limit are not functioning as expected.

The error message appearing in the console is:

TypeError: Cannot read property 'slice' of undefined

Below are the relevant parts of my code:


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

    app.service('tableService', ['$resource', function($resource){
            this.getTableData = function(id, email, date) {
                var tableDataList = $resource("table.json");

                return tableDataList.get ({
                    id: id,
                    email: email,
                    date: date
                })
            }
    }])

    app.controller('tableCtrl', function($scope, tableService, ngTableParams) {

                //Data
                $scope.id = tableService.id;
                $scope.email = tableService.email;
                $scope.date = tableService.date;

                $scope.dtResult = tableService.getTableData(this.id, this.email, this.date);


                $scope.tableParams = new ngTableParams({
                    page: 1,            
                    count: 10           
                }, {
                    total: $scope.dtResult.length, 
                    getData: function ($defer, params) {
                       $defer.resolve($scope.dtResult.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    }
                })

    });

HTML

<table ng-table="tableParams" class="table">
              <tr ng-repeat="w in dtResult.list">
                  <td data-title="'ID'">
                      {{ w.id }}
                  </td>
                  <td data-title="'Email Address'">
                      {{ w.email }}
                  </td>
                  <td data-title="'Date'">
                      {{ w.date }}
                  </td>
              </tr>
</table>

You can access the Plunkr version here.

I would appreciate any assistance with resolving this issue. Thank you.

Answer №1

Modify this within tableService

 let tableListData = $resource('data-table.json',{ }, {
        fetchInfo: {method:'GET', isArray: false}
      });

Answer №2

The reason why this is occurring is because when you receive the return from the service, it includes the $promise which takes time to ensure that the data is guaranteed.

Take a look at the code where I made some modifications and then continue with your other tasks.

Access the Plunker link here

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

app.service('tableService', ['$resource', function($resource){
    this.getTableData = function(id, email, date) {
        var tableDataList = $resource("table.json");

        return tableDataList.get ({
            id: id,
            email: email,
            date: date
        }).$promise;
    }
}])

app.controller('tableCtrl', function($scope, tableService, ngTableParams) {

    //Data
    $scope.id = tableService.id;
    $scope.email = tableService.email;
    $scope.date = tableService.date;

    tableService.getTableData(this.id, this.email, this.date).then(function(data){
      console.log(data);
      $scope.dtResult = data.list;
      $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10           // count per page
    }, {
        total: $scope.dtResult.length, // length of data
        getData: function ($defer, params) {

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

    });



});

Answer №3

$scope.dtResult is initialized with the result obtained from making a get request using a $resource:

$scope.dtResult = tableService.getTableData(...)

Later on:

$scope.dtResult.slice(...)

The error likely originates from the line above.

As per the documentation: "It is crucial to understand that invoking a $resource object method immediately returns an empty reference (object or array based on isArray)." -- This indicates that initially, $scope.dtResult will be an empty object here (it will be populated once the get call fetches some results). Perhaps switching to using query instead of

get</code could solve the issue and ensure the result is in an array format?</p>

<p><strong>EDIT:</strong></p>

<p>After reviewing the latest plunkr mentioned in the comments, the specific error is <code>TypeError: undefined is not a function
. This contrasts with the original issue raised. While dtResult exists, it does not have a slice function. Given the data structure (as seen in the plunkr):

{
  list: [
    {...},
    ...
  ]
}

There's an object containing a list, and this list should be displayed in the table.

In this scenario, the workaround provided by $resource to avoid callback usage may not apply (where an initial empty object/array is returned before getting updated with fetched details later). Directly utilizing the $promise, as recommended by @Akshay Dhankhar in another answer, seems necessary. The "official" example for server-side list with ng-table demonstrates a similar approach.

Hence, rather than calling tableService.getTableData upfront, perform it within your getData function and resolve the deferred object for the table upon receiving the actual result:

// no need for this: $scope.dtResult = tableService.getTableData(this.id, this.email, this.date);

$scope.tableParams = new ngTableParams({
    page: 1,            // show first page
    count: 10           // count per page
}, {
    getData: function ($defer, params) {
      tableService.getTableData($scope.id, $scope.email, $scope.date).$promise.then(function(data) {
         params.total(data.list.length);
         $defer.resolve(data.list.slice((params.page() - 1) * params.count(), params.page() * params.count()));
      });
    }
})

In the HTML, utilize $data as your list:

<table ng-table="tableParams" class="table">
    <tr ng-repeat="w in $data">
        <td data-title="'ID'">
        ...

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 Material-ui Autocomplete where the defaultValue does not function properly

The defaultValue was set to "Chairs" but it doesn't seem to be working as expected. Here is the code snippet: import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomple ...

JavaScript 'await' throws error 'then is not defined'

Just starting out with async programming and I've noticed a common issue in similar threads - the problem of not returning anything. However, in my case, I am facing a different error message 'Cannot read property 'then' of undefined&ap ...

Displaying the data from a database on a browser using node.js, MySQL, and Jade

Currently, I am delving into Node.js, Express.js, and Jade while utilizing a MySQL database. As a newcomer to node.js, I decided to start with something simple: presenting data from the database in a table on the browser. Unfortunately, my attempts have no ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...

The Angular2 component link imported in the core.module is not functioning properly

Adhering to the guidelines provided in the Angular style guide found at https://angular.io/styleguide#!#04-11, I have created a simple navigation setup. My app.component contains links like <a routerLink="hello">hello</a>, which work perfectly ...

Dealing with multiple POST requests at once in Node Express JS - Best Practices

I've been working on a Node project with Express to handle incoming GET/POST requests. I have set up routes to manage various types of requests. One specific route, /api/twitter/search, calls a function that uses promises to retrieve Twitter feeds and ...

Is it possible for JavaScript to access and read a local file from a web page hosted locally

I am interested in using html, css, and javascript to develop a user interface for configuring a simulation. This interface will be used to generate a visualization of the simulation and an output parameters file based on multiple input files. It is impor ...

Prevent a HTML button from being clicked multiple times before it disappears (using Django)

I am currently working on a Django project that involves events where users can join by adding their user_id and event_id to the attend model. On the event page, there is a join button form that, when clicked, adds the user to the attendees list. After cli ...

What is the process of exporting a module that has been imported in ES6?

Here are 3 code snippets: // ./src/index.ts const myApp = { test: 1, ... } export default myApp // ./src/app.ts import myApp from './src/index' export default myApp // ./index.vue import { example } from './src/app.ts' console.l ...

Material-UI: The `paperFullWidth` key passed to the classes prop is not supported within the WithStyles(ForwardRef(Dialog)) component

When using Material-UI, please note that the key paperFullWidth provided to the classes prop is not implemented in WithStyles(ForwardRef(Dialog)). You are only able to override one of the following: root. <Dialog classes={{ paperFullWid ...

Building a Next.js application in a docker container on a local machine using minikube is successful, however, the build fails when attempting to build it on a staging environment

I've encountered a puzzling issue. My next.js app is running in a docker container. It builds successfully on my local Ubuntu machine with minikube and ks8 orchestration, but it gets stuck indefinitely during the build process on the staging setup. T ...

Choose the current parent item using Angular's ng-selected and $index

http://plnkr.co/edit/fwwAd4bn6z2vxVN2FUL7?p=preview On the Plunker page linked above, I am trying to achieve a specific functionality. I would like the 3 dropdown lists to display values A, B, and C initially. When a 4th dropdown option is added, it shoul ...

Customizing the jQuery Datepicker to only allow a predefined set of dates

I am looking for assistance regarding the jQuery datepicker. I have an array of dates and I need to disable all dates except for the ones in this specific array. Currently, the code I have does the opposite of what I need. I generate the array of dates in ...

What is the process for transforming an asynchronous method into a synchronous version?

I am currently working on creating a functionality similar to the core fs module's methods, where there is an Async method by default and a Sync method if requested like fs.readDir() and fs.readDirSync(). In my case, I have a method named fetchUrls w ...

Using JavaScript to listen for events on all dynamically created li elements

Recently, I've created a simple script that dynamically adds "li" elements to a "ul" and assigns them a specific class. However, I now want to modify the class of an "li" item when a click event occurs. Here's the HTML structure: <form class ...

Guide to showcasing an image on an HTML page using HTTP header

I have an HTML page with a basic layout that includes a single button. When this button is clicked, it needs to trigger an HTTP request to a specific URL while including an Accept header for GET requests. The response from the HTTP URL will vary depending ...

Update the value of input within a Struts2 iterator by utilizing JavaScript

As a junior programmer, I am trying to update the value of an input type text within a Struts2 iterator without refreshing the entire page. I believe using JSON could be a solution for this issue. Here is my JSP code: <input type="text" name="cantidad ...

Content within a Row of a Data Table

Hello! I am just starting to learn JavaScript and jQuery. Can you help me with an issue I am experiencing? Basically, I have a table and I need to identify which tr contains a td with the text "Weekly", "Daily", or "Monthly". Once I locate that specific t ...

Leveraging partials on their own

I am currently exploring the possibility of loading a partial in linkedin-dustjs without having to load its parent along with it. For instance, consider this partial (login.dust): {>layout/} {<content} <!-- Login Screen --> {/content} Th ...

The Angular view fails to refresh after the second invocation of $compile

I am currently working on a modal pop up feature in my code. Here is a sneak peek at the view: <div class="modal fade in bs-example-modal-lg quickview__modal__bg" id="productModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" ng-controlle ...