Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the grid with the fetched data. I need a way to asynchronously retrieve data from a service and use it to populate my grid. How can this be achieved?

In my app.js file:

var app = angular.module('myApp', ['ngGrid']);
//service call to get the data
app.service('MyService',function($http){
   var get = function(){
       return $http.get('data.json');
   }
    return {
        get: get
    }
});

//controller where the grid is located
app.controller('NewController',function($scope,MyService) {
    $scope.get = MyService.get;
    $scope.message = "this is the new controller message";
    $scope.gridOptions = {
        data: $scope.get
    }
    var getData = function() {
        $scope.get().then(function (data) {
            $scope.gridOptions.data = data['data'];
            console.log('from the success handler');
            console.log($scope.gridOptions.data);
        }, function (reason) {
            console.log('failed: ');
            console.log(reason)
        })

    }
    getData();
});
//not relevant in this example
app.controller('MyCtrl',function($scope){
    $scope.data = "This is some data";
})

For the HTML:

<html ng-app="myApp">
<head lang="en">
    <meta charset="utf-8">
    <title>Getting Started With ngGrid Example</title>
    <link rel="stylesheet" type="text/css" href="css/ng-grid.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <script src="libs/jquery-1.9.1.js"></script>
    <script src="libs/jquery-ui-1.9.1.custom.min.js"></script>
    <script src="libs/angular-1.2.js"></script>
    <script src="libs/ng-grid-2.0.11.debug.js"></script>
    <script src="scripts/app.js"></script>
    <style>
        .gridStyle {

            width: 400px;
            height: 300px
        }
    </style>
</head>
<body >


<div ng-controller="NewController">
    <div class="gridStyle" ng-grid="gridOptions"></div>
</div>
</body>

No errors are showing up in the console, but it appears that the gridOptions are not being set as expected in the success handler. The data being received is correct, and all logs show up fine in the console. How can I effectively utilize my service to populate an ngGrid table?

Answer №1

When using ng-grid, it is important to set up your data source properly.

tutorial

Here are some corrections for your code:

$scope.gridOptions = {data:'myData'};

Make sure your data source is an array:

$scope.myData = dataList['info'].array;

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

Only one bootstrap collapse is visible at a time

Currently, I am using Bootstrap's collapse feature that displays content when clicking on a specific button. However, the issue I am facing is that multiple collapses can be open at the same time. I want to ensure that only one collapse is visible whi ...

When using $.ajaxSetup, the content type is not configured for Get requests

Snippet 1 $.ajax({url:"1.aspx/HelloWorld",type:"GET",dataType:"json",contentType:"application/json"}); Snippet 2 $.ajaxSetup({ contentType: "application/json", dataType: "json" }); $.get( ...

What is the recommended approach for passing parameters to a JavaScript function from an anchor tag?

I recently came across this intriguing question: What is the best practice for using Javascript and Anchor Tags? The suggestion provided in response to this query involves utilizing the following code snippet: <a id="foo" href="#">Click Me</a&g ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

Elevate state in React to modify classNames of child elements

I have a structured set of data divided into 6 columns representing each level of the hierarchy. When a user makes selections, their chosen location is highlighted with a dynamic CSS class name and displays the relevant data list. I've managed to impl ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

Unable to add a string to a http get request in Angular

When a specific ID is typed into the input field, it will be saved as searchText: <form class="input-group" ng-submit="getMainData()"> <input type="text" class="form-control" ng-model="searchText" placeholder=" Type KvK-nummer and Press Enter" ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

Facing a challenge with displaying an angularjs template within a popover

I am having trouble displaying custom HTML content in a popover when clicking on my "View" link. Although other content is rendering correctly, such as one with an ng-repeat inside it, my custom directive does not seem to be processed and displayed properl ...

What is the best way to utilize delayed_job?

After reviewing the documentation, I am struggling with integrating it into my application. Currently, users input a video URL, which is converted into a link in the view. Then, I utilize the Embedly API to transform that link into an embedded video, alo ...

Looking to streamline a JavaScript function, while also incorporating jQuery techniques

I've got this lengthy function for uploading photos using hidden iFrames, and while it does the job well, it's quite messy. I'm looking to simplify it into a cleaner function with fewer lines of code for easier maintenance. function simplif ...

The communication between AngularJS and SignalR is experiencing issues

There seems to be a discrepancy between the functionality of jQuery and AngularJS in this scenario. While jQuery is able to return data on the client side successfully, AngularJS struggles to initiate or invoke the connection with the server. Any suggestio ...

Identical manipulator distinct infusion

I am looking to create multiple controllers that share the same logic, with only differences in injections. One way to achieve this is by creating controllers using a common function like so: var controllerFunc = function($scope, service) { $scope.se ...

Execute JavaScript function on click event in NextJS

Is it possible to execute a JavaScript function on the client side without using addEventListener? This situation works with addEventListener. MyComponent.js import Script from 'next/script' export default function MyComponent({ props }) { ...

Once an AJAX call is made, the state of a React component changes but fails to trigger a

In this section, users have the opportunity to comment on posts. Once the data is received and verified on the server side, I attempt to update the value of this.state.comments. However, there is an issue where the comment section in the component does not ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

Animate the sliding of divs using the JavaScript animation function

I've designed some boxes that function similar to notifications, but now I want to smoothly slide them in from the left instead of just fading in. I know that I need to use .animate rather than .fadeIn to achieve this effect. The code snippet I&apos ...

Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query: // customers.model.js CUSTOMERS.getAll = (result) => { let query = "SELECT * FROM custo ...

Generate a new object from the contents of a div

Having the HTML structure below: <div id="main"> <div id="myDiv1"> <ul> <li>Abc</li> <li>Def</li> </ul> </div> <div id="myDiv2"> <ul> <li>Ghi</l ...