Learn how to dynamically load columns and rows from an HTTP call in ag-Grid, allowing for both the column structure and data records to be flexible

My task involves allowing the user to click on a table name which will then render the corresponding data in ag-grid.

I am currently using AngularJS 1.x and have tried various methods to achieve this.

$scope.gridOptions = {};
$scope.loadTableInGrid = function (tablename) {
    $http.post($scope.url + "/getPagingRecordImportedTable", { 'dbname': $stateParams.dbname, 'tableName': tablename, 'pageNumber': 1 }).success(

        function (response) {

            $scope.names = response.records;
            $scope.mdata = response.metadata;

            console.log(response.records);
            console.log(response.metadata);

            var columnsize = 0;
            for (var obj in $scope.mdata) {
                if ($scope.mdata[obj]['columnsize'] > 20) {
                    columnsize = 20;
                } else {
                    columnsize = $scope.mdata[obj]['columnsize'];
                }

                $scope.columnDefs.push({
                    "headerName": $scope.mdata[obj]['columnname'],
                    "field": $scope.mdata[obj]['columnname']
                });
            }


            var gridDiv = document.querySelector('#myGrid');
            alert(gridDiv);
            new agGrid.Grid(gridDiv, $scope.gridOptions);
            $scope.gridOptions.api.setColumnDefs( $scope.columnDefs);
            $scope.gridOptions.api.setRowData(response.records);
            $scope.gridOptions.api.refreshView();



            console.log("-----------Data received");
        }).error(function (data) {
            alert(data);
        });
    } else {
        $scope.reset();
        $scope.resetGridTableName();

    }
    console.log(tablename);
};

Based on the table name provided, I need to dynamically load both columns and records in the grid. However, it consistently displays "loading" without rendering any data.

If you have any examples or suggestions for improving my code, please share them with me.

Answer №1

It seems like there is 1 if statement and 2 else statements in the code you provided... Is there something missing?

On a different note, when using Angular's ajax method, it returns a Promise which should be handled with .then/.catch instead of .success/.error

A possible alternative implementation could look like this: (please note that this is untested) (and involves ES6 arrow functions and const)

$scope.gridOptions = {};
$scope.loadTableInGrid = tablename => {
    const url = $scope.url + "/getPagingRecordImportedTable"
    const formData = {
        dbname: $stateParams.dbname,
        tableName: tablename,
        pageNumber: 1
    }

    console.log(tablename);

    $http.post(url, formData)
    .then( response => {
        $scope.names = response.records;
        $scope.mdata = response.metadata;

        console.log(response.records);
        console.log(response.metadata);

        var columnsize = 0;
        for (var obj in $scope.mdata) {
            if ($scope.mdata[obj]['columnsize'] > 20) {
                columnsize = 20;
            } else {
                columnsize = $scope.mdata[obj]['columnsize'];
            }

            $scope.columnDefs.push({
                headerName: $scope.mdata[obj]['columnname'],
                field: $scope.mdata[obj]['columnname']
            });
        }

        var gridDiv = document.querySelector('#myGrid');
        alert(gridDiv);
        new agGrid.Grid(gridDiv, $scope.gridOptions);
        $scope.gridOptions.api.setColumnDefs($scope.columnDefs);
        $scope.gridOptions.api.setRowData(response.records);
        $scope.gridOptions.api.refreshView();

        console.log("-----------Data received");

    }).catch( err => {
        console.log( "Error: ", err )
    })
};

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

Error encountered when attempting to use Gridsome for Vue.js project construction

Currently, I am utilizing Vue.js and Gridsome to craft a personalized portfolio. However, an issue arose when I attempted to incorporate a JSON file to store my profile details on the site. Here is how I imported the file within my Index.vue component: &l ...

Manipulate image position with touchmove event using CSS3 transformations on an iPad

Looking to adjust the position of an image on my iPad3, but running into some difficulties. The movement isn't as smooth as desired and seems to lag behind the gestures being made. This is what I have so far (a 3MB base64 image) <img src="data:i ...

What exactly is the purpose of utilizing node js and can someone explain to me what constitutes a

After mastering HTML and CSS, I've started diving into JavaScript. However, I'm curious about Node.js. What exactly is it, why do I need it, and can you explain what a framework is in general? Sorry if these questions sound silly! ...

Error: The attempt to access the 'useContext' property of null has failed due to a TypeError

Nowhere in my React code am I using the useContext property. There is a compiled webpack file in an npm package with a component inside. When trying to use this component in my React app, it throws an error: Uncaught TypeError: Cannot read properties of nu ...

Is it possible to replicate the jQuery scrollTo functionality using AngularJs?

I am currently working on a single-page website where I want to navigate to the respective div with scrolling when clicking a tab. I have come across the scrollTo jQuery function for this purpose. However, I am curious if it is possible to achieve the sa ...

Issue encountered when attempting to use array.sort on values exceeding 1000

When I use the .sort() method on my firstArr example, it functions correctly. However, when I apply the .sort() method to secondArr, which contains values exceeding 1000, it malfunctions. I have attempted to locate information on any limitations of the . ...

Pull JSON data from an Ajax application and cycle through the JSON values in a separate function

As I delve into the world of Ajax, I find myself grappling with a particular issue - the feasibility. My current endeavor involves fetching data from a db.json file using Ajax. { "transactions": [ { "date": "4/3/2021", "description": "Electric bill", ...

What is the best way to halt a window.setInterval function in JavaScript?

I have a JavaScript function that runs every 2000ms. I need to find a way to pause this function so that the user can interact with other elements on the page without interruptions. Is there a way to achieve this? Below is the code for the function: win ...

Tips for swapping content between table rows in JavaScript

Struggling to rearrange a table with a new order due to performance issues. Here is a simplified version of the structure: <table> <tr id="row1"></tr> <tr id="row2"></tr> <tr id="row3"></tr> <tr id="row4">&l ...

Organizing information in local storage using an array and converting it to a string

After storing user inputs (Worker's name, Car Vin, Start time and End time) in the local storage, you want to sort the employees' names in alphabetical order. The question is where should the code be placed and how should it be written? // Car C ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

Vue PWA - manifest.json replaced upon refreshing the page

I'm encountering an issue with my Progressive Web App (PWA) where reloading the page manually or redirecting using window.location results in the manifest.json file being overwritten with the contents of index.html. This leads to an error stating Mani ...

There was an error in reading the 'nativeElement' property in Angular's waveform library, resulting in a TypeError

This is the code I wrote, but it is showing an error: The waveform should be created, but the function to create the waveform is not working. startRecording() { this.mediaSectionVisible = false; if (!this.isRecording) { this.isRecording = t ...

Use JavaScript to change the CSS pseudo-class from :hover to :active for touch devices

Looking to eliminate hover effects on touch devices? While it's recommended to use a hover class for hover effects, instead of the hover pseudo-class, for easier removal later on, it can be a challenge if your site is already coded. However, there&apo ...

What is the best way to dynamically add a class to the right navigation element in Vue.js when the :class binding only accepts boolean values?

My issue involves implementing a fixed navigation bar with the following structure: <nav class='navigation'> <div :class="{ active: }" @click='scrollTo(".test1")'></div> <div :class=" ...

Issues with Minor Code Problems in Node.js - Need for Exported Functions

Following a Previous Update: We Are Invoking a Function in this Way var lastUsedRoute = appNavigator.getLastUsedRoute(); Where appNavigator is var appNavigator = require("app_utils/default/app-navigator"); and app-navigator includes an export like the fo ...

A guide on leveraging React TypeScript to pass components as props

Currently, I am in the process of learning React combined with TypeScript. However, I have encountered a challenge that I need assistance with. The issue stems from a parent component: import React from 'react'; import TestPropsComponent from & ...

Implementation of the I18next library

I am currently integrating react-i18next into my application to implement a switch button for French and English languages. Unfortunately, I am facing some issues as the translation is not working properly. I suspect it's related to the JSON file reco ...

Implementing Bootstrap attributes into a personalized Vue.js component

I have been tasked with incorporating a new html page into a vuejs project. The page is fully developed and utilizes jquery along with various elements from twitter-bootstrap. I have created a new component. NewPage.vue <template> <div id=" ...

Problem with ng-repeat and custom directive in the header row

I'm currently in the process of transitioning our thead generation to a directive. However, I've noticed that when using this directive, the headers lose their styling and become clustered on the left side. Can anyone provide some assistance on w ...