AngularJS - Ng-Table - Undefined

I'm facing difficulties when trying to create an ngTable. I can successfully render manually created arrays, but when I connect it to my api, it fails without any error message which is confusing. The $scope.data array is being filled as expected, but the new tableParams always ends up undefined.

Below is my HTML code:

<div ng-app="myApp" class="container-fluid" ng-controller="demoController as demo">
    <div class="row">
        <div class="col-xs-12">
            <h2 class="page-header">Pharmacy Rebate Portal</h2>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <h3>Default configuration</h3>
            <table ng-table="demo.tableParams" class="table table-condensed table-bordered table-striped">
                <tr ng-repeat="row in $data">
                    <td data-title="'Manufacturer'">{{row.manufacturer | uppercase }} </td>

                </tr>
            </table>
        </div>

    </div>
</div>

I'm using ngTable version and Angular version 1.6.3. Any suggestions or ideas on how to resolve this issue?

$http.get('/api/rebates').
            then(function (response) {
                $scope.data = response.data;
                $scope.tableParams = new NgTableParams({
                    page: 1,            // show first page
                    count: 10,          // count per page
                    sorting: {
                        foo: 'asc'     // initial sorting
                    }
                }, {
                        total: $scope.data.length, // length of data
                        getData: function ($defer, params) {
                            // use build-in angular filter
                            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()));
                        }
                    });
            });`

Answer №1

JavaScript is synchronous by nature. This means that in the code snippet provided, the line $scope.data=response; is being executed before the request made with $http.get('/api/rebates')... has a chance to complete. As a result, $scope.data ends up being undefined. To address this issue, I suggest utilizing a Service to handle the asynchronous data retrieval.

var myApp = angular.module('myApp', []);
  myApp.controller('AppCtrl', ['$scope', '$http', 'dataService', function($scope, $http, dataService){

  dataService.getDataLists(function(response) {
    console.log(response.data);
    $scope.data=response.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()));
                        }
                    });
  });

});
}])

myApp.service('dataService', function($http) {
    this.getDataLists = function(callback){
   $http.get('/api/rebates').then(callback)
  }
});

Answer №2

It appears that using the $ sign is causing the error. Have you attempted the following:

<tr ng-repeat="row in demo.data">

Update:

Although not tested, I believe this is the correct approach:

$scope.tableParams = new NgTableParams({
  page: 1,
  count: 10,         
  sorting: {
    foo: 'asc'
  }
}, 
{
  getData: function(params) {
    return $http.get('/api/rebates')
      .then(function(response) {
        var orderedData = params.sorting() ?
                          $filter('orderBy')($scope.data, params.orderBy()) :        
                          $scope.data;

        return orderedData.slice((params.page() - 1) * params.count(),  
                                 params.page() * params.count());
      });
});

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

Ways to manage an excessive number of asynchronous calls?

As a newcomer to Node, I've learned that writing synchronous functions can negatively impact the event loop by causing it to lock up. It's generally better to write everything asynchronously. However, there are cases where using async for everyt ...

Troubleshooting a Peculiar Problem with Form Submission in IE10

Please take a look at the code snippet provided below: <!DOCTYPE html> <html> <body> <form name="editProfileForm" method="post" action="profileDataCollection.do"> <input type="text" id="credit-card" name="credit-card" onfocu ...

Warning: Attention Required for Published NPM Package Fix

After successfully publishing my first package on npm, I encountered a warning when I tried to import it in Codesandbox. There was an error converting '/node_modules/protected-react-routes-generators/src/index.js' from esmodule to commonjs: Canno ...

In node.js, what is the syntax for invoking a function within a struct from that same function?

Here is a brief overview of my code: exports.entity = { name: "Foo", //Etc... start: function () { this.attack(); }, attack: function () { setTimeout(attack, 1000); //Doesn't work ...

Exploring AngularJS Navigation in Windows 8 App Store Applications

Hello, I recently started learning about developing Windows Store apps. I found a way to incorporate AngularJS into my Windows 8 store app by making some adjustments in the AngularJS library. However, I'm now struggling with implementing AngularJS rou ...

JavaScript Class Reference Error

Questioning the mysterious reference error in the JS class from MDN page. The structure of the Bad class's constructor leaves me baffled – is it because the empty constructor calls super() as a default? class Base {} class Good extends Base {} cla ...

Is there a way for me to connect the ajax data to Vue components?

Utilizing Jquery ajax to load data from an external API has been successful and the v-for text is also working without any issues. Vue var vm = new Vue({ el:'.inlinePoetry', data:{ PoetryList:[] }, created:function(){ var ...

403 Forbidden - CSRF Token Not Recognized

I am encountering an issue with Node Express and CSurf - 403 (Forbidden) Invalid csrf token. After reviewing other solutions and attempting all available options, I am still unable to resolve this. The API functions perfectly when tested in Postman. Howe ...

"Exploring the interactivity of touch events on JavaScript

Hi there, I'm currently facing an issue with the touch events on my canvas. While the mouse events are functioning correctly and drawing as expected, incorporating touch events seems to be causing a problem. When I touch the canvas, the output remains ...

A guide on simulating an emit event while testing a Vue child component using Jest

During my testing of multiple child components, I have encountered a frustrating issue that seems to be poor practice. Each time I trigger an emit in a child component, it prompts me to import the parent component and subsequently set up all other child co ...

Serve up a 400 error response via the express server when hitting a

I need help serving a 400 error for specific files within the /assets directory that contain .map in their names. For example: /assets/foo-huh4hv45gvfcdfg.map.js. Here's the code I tried, but it didn't work as expected: app.get('/assets&bs ...

What steps are needed to enable the keyboard on a Otree application for mobile devices?

I previously utilized an Implicit Association Task (IAT) in an experiment conducted on computers. However, I now need to adapt this IAT for use on tablets or mobile devices. Here is how the IAT appears on a cellular device: https://i.stack.imgur.com/kNwo ...

Tips for accessing a unique window name in JavaScript

How can I make window.name persist between page refreshes? I need to use window.name to differentiate between multiple browser windows, allowing each one to display distinct data while sharing the same URL. However, my problem is that the value of window ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

Reactive property cannot be defined on an undefined, null, or primitive value within the context of Bootstrap Vue modal

Can someone please assist me with this error message? It says "app.js:108639 [Vue warn]: Cannot set reactive property on undefined, null, or primitive value." I encountered this error while working with a Bootstrap Vue modal. Here is a snippet of my code: ...

AngularJS: How can you make one element update another element's view if they share the same controller?

Here is the setup in my index.html: <div id="div1" ng-controller="StartMenu"> <div id="button1" ng-click="doSomething()"></div> {{value}} </div> <div id="div2" ng-view></div> Setting up the module: angular.module( ...

Puppeteer: Locating elements using HTML attributes

I'm currently working on getting Puppeteer to locate an element on this webpage using its attribute data-form-field-value, which needs to match 244103310504090. Here is the HTML code for the button in question: <section class="fl-accordion-tab--c ...

What is the best way to retrieve data based on conditions in React?

I'm currently learning React and trying to pass props from a parent component (table row) to a child Modal component. Inside the child component, I want to fetch data based on the props provided. I have created a custom hook called useFetch that store ...

What is the best way to retain selection while clicking on another item using jQuery?

There is a specific issue I am facing with text selection on the page. When I apply this code snippet, the selected text does not get de-selected even after clicking .container: jQuery('.container').on("mousedown", function(){ jQuery('. ...

Enabling Cross-Origin Resource Sharing in Node.js 14

I'm diving into the world of JavaScript and Node.js as I work on creating a new REST-based API using NodeJS. However, I've hit a roadblock when trying to fetch data from the API due to a CORS issue. Browser console error message: Access to fetch ...