When exchanging information in Angular UI-Grid, newly added columns may not appear when modifying the dataset from an external source

I have developed a query tool with an angular form that is filled out and submitted using AJAX to retrieve JSON data. This JSON response is then rendered into ui-grid. Here's an example of the JSON response:

{
"success": true,
"message": "",
"columns": ["first_name", "last_name", "company", "employed"]
"results": [
    {first_name: "John", last_name: "Smith", company: "Abc Inc", employed: true},
    {first_name: "Johnny", last_name: "Rocket", company: "Abc Inc", employed: true}]
}

While working on both the PHP and angular components, I encountered an issue where if a new dataset is retrieved through a separate AJAX call on the same page, any columns not present in the original dataset do not render. This causes problems as the table is essentially cleared when there are no matching columns, even though I often need to display completely different data in ui-grid within the same page.

Upon receiving the JSON data, I simply bind the jsonResult.results to the existing $scope.myData variable which ui-grid is connected to.

I have created a plunker to demonstrate this issue. The initial dataset has a "punk" column, and by clicking "swap data," an attempt is made to load a dataset with an "employee" column instead of "punk." I have explored solutions such as directives to refresh or reload when the $scope.myData variable changes using $watch, as well as investigating options like $scope.columnDefs to inform ui-grid. However, as someone relatively new to angular and javascript, some of these concepts are still challenging for me to grasp.

Answer №1

I have made some adjustments to your plunker:

$scope.switchData = function() {
  if ($scope.gridOpts.data === data1) {
    $scope.gridOpts.columnDefs = [
      { name:'firstName' },
      { name:'lastName' },
      { name:'company' },
      { name:'worker' }
    ];
    $scope.gridOpts.data = data2;
    //worker column changes to employee
  }
  else {
    $scope.gridOpts.columnDefs = [
      { name:'firstName' },
      { name:'lastName' },
      { name:'company' },
      { name:'employee' }
    ];
    $scope.gridOpts.data = data1;
    //employee column changes to worker
  }
};

http://plnkr.co/edit/OFt86knctJxcbtf2MwYI?p=preview

Given that you already have the columns in your JSON, it should be quite simple to implement.

Answer №2

After studying Kevin Sage's answer and analyzing the plunker example, I made an additional discovery. When using the backward-compatible "field" attribute for swapping data in column definitions, issues arise if there are overlapping field names. This results in incorrect rendering of column headers and widths. To resolve this problem, use the "name" attribute instead.

    $scope.switchData = function() {
  if ($scope.gridOpts.data === data1) {
    $scope.gridOpts.columnDefs = [
      { name:'firstName' },
      { name:'lastName' },
      { name:'company' },
      { name:'employee' }
    ];
    $scope.gridOpts.data = data2;
    // Change from punk to employee
  }
  else {
    $scope.gridOpts.columnDefs = [
      { name:'firstName' },
      { name:'lastName' },
      { name:'company' },
      { name:'punk' }
    ];
    $scope.gridOpts.data = data1;
    // Change from employee to punk
  }
};

See the working example: Plunker

Answer №3

This is how I solved it:

$http.get('url').success(function(response) {
// clearing existing data
gridOptions.data.length = 0;
// updating data in the next digest cycle 
$timeout(function() {
gridOptions.data = response;
});
});

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

Receiving the error message "Encountered issue reading property of 0" while attempting to retrieve a specific element from an array

Currently, I am facing an issue where I am trying to access a value that is set in one function within another function. When I attempt to return this value at the end, the console.log displays the value correctly. However, when I try to set it, I receive ...

Changing the filepath for the build script in the package.json file for a NextJS project when deploying to Heroku

My project is currently structured as Root: Folder 1/ Folder 2/ Folder 3/ .. Frontend/ The front end folder contains my Nextjs project, package.json file, and everything else. However, Heroku requires the content in the Frontend/ folder to be in the root ...

How can I retrieve text adjacent to a checked input checkbox by using JQuery (or JavaScript)?

Here is the HTML block under consideration: <div class"radioGroup"> <input type="radio" value="0"> This option is NOT selected <input type="radio" value="1" checked = "checked" > This option is selected <inpu ...

Ajax request triggers a page refresh

As I review the AJAX call within a React method, there are some key observations: handleActivitySubmit: function handleActivitySubmit(activity, urlActivity, callbackMy) { console.log("querying with activity: " + JSON.stringify(activity)); $.ajax ...

Executing untrusted JavaScript code on a server using a secure sandbox environment

I am facing difficulties in creating a secure node sandbox that can execute untrusted code while allowing users to communicate with the program through api calls (input and output). My goal is to establish a browser console where users can run their own se ...

What is the best way to paginate aggregated results in Mongoose?

In my project, I have a User model that is linked to two other associated models - Profile and WorkProfile. The Profile model contains basic information about the user like name, email, and home address, while the WorkProfile model stores details such as o ...

Tips for Implementing the `otherwise` Function in Angular 2's UI-Router

When working with ui-router in AngularJS, we can use the otherwise function to handle invalid or unregistered states. For example: $urlRouterProvider.otherwise('/index'); This means that any invalid URL will be redirected to /index. But how do ...

"Mastering the art of sending a request to the server using AJAX with the

Here is some of my code in HTML: function loadDoc(){ var num = '{"empid": 45,"name": "gaurav","salary":566.55}'; $.ajax({ url: 'http://localhost:9029/addS', method: 'POST', data: num, success: function(response){ co ...

The issue persists with Angular routing as the page does not load even when adding a template, resulting in nothing being

Can someone please help me figure out why I am having trouble routing the app.js file? (function () { "use strict"; var app = angular.module("productManagement", ['ngRoute']); app.config(['$routeProvider', '$locationPr ...

What are some ways to bypass a closed Google form that is no longer accepting responses? I need to find a way to submit my form even after the deadline

Is there a way to trick a closed Google form that says it is "no longer accepting responses"? I'm looking to submit a form past the deadline. Is there a method to access and submit a form that has already been closed? The code for the closed form appe ...

The mysterious case of the disappearing items: why does Firebug show a blank array of objects in JavaScript and AngularJS?

Here is a problem that I am facing with JavaScript and cannot seem to figure it out from the screenshot below. The issue I'm encountering is that when checking the array in firebug, it appears to be blank with a length of 0. However, if I click on th ...

Verifying if form submission was done through AJAX using PHP

Hey there, I need some help with checking whether or not this ajax method has been submitted. I want to display the result based on a certain condition. Below is the code for the Ajax POST request: $.ajax({ url: "addorderInfo.php", // This ...

Tips for transferring the id from a delete button to a delete button in a popup dialog box

In my frontend application, there is a table where each row corresponds to an item. For every row, there is a "Remove" button that triggers a warning popup upon being clicked. The intention is to pass the item's ID in this popup so that if the user co ...

Replace Vue's mixin function

Is it possible to overwrite one of npm's mixins that is used within a component with a local mixin? I have a component from an npm package located in node_modules/somePackageName/components/footer.vue which uses a mixin from node_modules/somePackageN ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

Is it possible to perform direct URL searches using react-router-dom?

Encountering an issue when attempting to directly copy a route, resulting in the following error: Error: Cannot Access / home Despite utilizing various methods such as browserHistory, I am unable to successfully render views when navigating with menu i ...

Is there a way to access the contents of ng-repeat using getElementById?

Is there a way to extract the data from ng-repeat? <div ng-repeat="w in quick.wint"> <div id="wname"><strong>{{w.Name}}</strong></div> <div id="wcount">{{w.Count}} Open Queues</div& ...

Issue with mouseout gap in Microsoft Edge when using the <select> element

A noticeable gap appears in Microsoft Edge between the <select> menu and its options when expanding the menu, as shown here: https://i.stack.imgur.com/SprJ2.png This particular issue can cause problems with the mouseout event due to inconsistent be ...

When invoking the jQuery ".load('pageName')" method, HTML pages are not loaded from the application cache

I have been working on incorporating the html5 offline caching functionality into our html pages, and everything seems to be running smoothly with jQuery version 1.4. However, I encountered a problem when I upgraded to jQuery 1.8. Specifically, issues aro ...

What is the process for uploading an image using fetch?

After just starting to learn react, I decided to create a gallery App. However, I am facing an issue when trying to post pictures to the API. Whenever I click on the ADD button, nothing happens except for an error 500 being logged in the console. Below is ...