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

When a npm package consists of multiple files, what is the best way to import them?

I have an npm package that consists of three files in the dist folder, generated by webpack: https://i.sstatic.net/td5Us.png Within the package.json file, I have designated the sample.js file as the main one: "main": "dist/sample.js", ...

The error message 'mainController' is not recognized as a function and is undefined, version 1.4

When it comes to utilizing newer angular directives like ng-blur, ng-focus, and form validation, the examples abound. They typically perform well in a standalone page or interactive coding platforms like plinkr and jsfiddle. However, there's one commo ...

Determine the item in a collection of objects that contains a specific key

What is the most efficient method for locating an object by a specific key in JS when given an array of objects? Utilizing jQuery and underscoreJS is acceptable. I am simply seeking the simplest solution with minimal code. Illustration: Suppose we have a ...

Obtain every possible sequence of US phone number segments for a provided number

The format of a US phone number is as follows: (XXX) XXX-XXXX Given a string consisting only of digits with a length between 0 and 10, I want to generate an array of all possible chunks that match the US phone number format. For example: Input: "54" Out ...

Is there a way to utilize the reset() function within an input form?

Is there a way to automatically reset the textbox when submitting a value? Below is my code: <!DOCTYPE html> <html> <body> <ul id="myList"> </ul> <input type="text" id="myText" value="&q ...

What is the best way to isolate a single element within a for loop and exclude all others?

I have implemented a dynamic Ajax call to compare the string entered in the text field (representing a city name) with the "type" value in a JSON array. As I iterate through the elements of the array, I am checking the values associated with the key "type ...

Warning: Nodemailer has issued a deprecation warning regarding the outdated `punycode` module

Looking to automate daily email sending through a Gmail account, I have been experimenting with nodemailer and crafted this simple test code: const fs = require('fs'); const path = require('path'); const nodemailer = require('nodem ...

What exactly does "nothing" mean in Node when using async await?

I have a method as shown below: private async sendToAll(clients) { for(const client of clients) { this.send(client, message); await true; // What should I put here to allow the rest of the application to continue executi ...

Having trouble with the locality function in Google Places v3 API autocomplete?

After successfully using the code below for about a week, I returned to work on it and found that it was no longer functioning properly. My goal is to only display localities. According to Google's documentation, "locality" is the correct option for a ...

VisualMap in ECharts featuring multiple lines for each series

If you'd like to view my modified ECharts option code, it can be found at this URL: Alternatively, you can also access the code on codesandbox.io : https://codesandbox.io/s/apache-echarts-demo-forked-lxns3f?file=/index.js I am aiming to color each l ...

Transmitting a Wav file from JavaScript to Flask

I'm currently working on a JavaScript code that records audio from the browser and now I need to figure out how to send it back to Flask. start: function () { var options = {audio: true, video: false}; navigator.mediaDevices.getUserMedia(optio ...

What sets Vuex apart from a traditional store object?

I'm currently utilizing Vuex for Vue 2 which is similar to Redux for React. Recently, I came across a helpful example that demonstrates updating a counter. Here is the code snippet: import Vuex from 'vuex' import Vue from 'vue' V ...

The data retrieved from the web API is not undergoing the necessary conversion process

I am facing an issue with a web API call where the property checkNumber is defined as a double on the API side, but I need it to be treated as a string in my TypeScript model. Despite having the property defined as a string in my model, it is being receive ...

When working with a set of objects, consider utilizing jQuery's InArray() method to effectively handle

Within my Javascript code, I am working with an array of Calendar objects. Each Calendar object contains an array of CalendarEvent objects. Every CalendarEvent object holds properties for Date and Name. I am looking to determine if a specific date exist ...

Is it recommended to utilize addEventListener?

Is it better to use the addEventListener method in these scenarios? <input id="input" type="file" onchange="fun()> or document.getElementById("input").addEventListener("change", function() { fun(); }); What are the advantages of using one over ...

Enhancing User Experience with Dynamic Table Layout in Angular

I need to create a table with the following object: this.customer = [{ cid:"1", productid:"1", src:"walmart", total:"1" }, { cid:"1", productid:"1", src:"target", total:"2 ...

Can you explain the functionality of $on.constructor in AngularJS?

Recently, I attempted an XSS challenge on the PortSwigger labs website. You can find the challenge here. This is my solution to the XSS challenge: {{$on.constructor('alert(1)')()}} However, since I have no prior experience with AngularJS, I&apo ...

onChange does not trigger useEffect

In the Order Content component, I am receiving some products as props to be used in a select component. When a product is selected in the dropdown, it triggers the rendering of Summary and Product components. In these components, the user can choose the ...

Parse the JSON data response as needed in ReactJS

var mydata = [ { source: 11, Registernumber: ">RT-113, <RT-333", jul1: 1004 }, { source: 11, Registernumber: ">RT-113, <RT-333", jul2: 1234 }, // Rest of the data entries... ]; Can we transform the above JSON ...

Unpredictable preset inline styles for HTML input elements

While developing a full-stack MERN application, I encountered an unusual issue when inspecting my React UI in Chrome DevTools. If any of these dependencies are playing a role, below are the ones installed that might be contributing to this problem: Tail ...