Using AngularJS to Extract JSON Data from a Table in an HTML Document

In the context of angularjs:

I have a table with 2 fixed columns (ID & Comment) and additional columns that are added dynamically by the user clicking a button. The user can input data into the rows of this table, and I need to extract/ read this data.

Here is a jsfiddle link for reference: http://jsfiddle.net/ajnh8bo5/7/

To add a new column, click on add tab, enter a name, and then click add columns

The javascript function to read the data looks like this:

  $scope.read = function() {
    return JSON.stringify($scope.targetTable);
  };

Currently, the generated JSON only includes information about the dynamically added columns. Sample JSON:

  {
    "id":0,
    "name":"Table 1",
    "columns":[
   {
    "id":0,
    "label":"Column 0",
    "$$hashKey":"object:11"
   }
    ],
"rows":[
 {
   "0":"2",
   "$$hashKey":"object:9",
   "undefined":"1",
   "id":1037
 }]

The JSON above represents one dynamically added column. In the "rows" array, "0":"2" indicates that the first dynamic column has a value of "2". However, it does not display data for the ID & Comment columns. I'm aware of a missing piece here but unsure about the next steps.

An additional feature, which is currently less essential, is to have the JSON output include column names.

---update---

The desired JSON output is as follows:

{
  "columns": [
    {
      "id": 0,
      "label": "ID"
    },
    {
      "id": 1,
      "label": "Column 1"
    },
    {
      "id": 2,
      "label": "Column 2"
    },
    {
      "id": 4,
      "label": "Comment"
    }
  ],
  "rows": [
    {
      "Id": "1",
      "Column 1": "2",
      "Column 2": "3",
      "Comment": "user comment"
    }
  ]
}

The above JSON outlines 2 static columns (ID & Comment) and dynamic columns Column1 & Column2.

If possible, I would like a solution based on the provided JSON structure. Alternatively, guidance on outputting static columns ID & Comment in the JSON would be helpful.

--Updated with relevant code---

Here is the HTML table structure:

<table class="table table-bordered" ng-if="targetTable">
        <thead>
          <tr>
            <th>ID #</th>
            <th contenteditable="true" ng-repeat="c in targetTable.columns" ng-model="c.label"></th>
              <th class="comment-fixed-width" ng-model="comment">Comment</th>
            <td class="center add-column fixed-width"><a ng-href ng-click="addColumn()">+ Add Column</a></td>
              <td class="comment-fixed-width" contenteditable="true" ></td>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="r in targetTable.rows">
            <td class="fixed-width" contenteditable="true" ng-model="r[column.id]"></td>
            <td class="fixed-width" contenteditable="true" ng-repeat="column in targetTable.columns" ng-model="r[column.id]" ng-blur="!r.id? addNewRow(r[column.id], r): undefined"></td>
             <td class="comment-fixed-width" contenteditable="true" ></td>
                                    <td class="blank fixed-width" colspan="2" ng-model="r[column.id]"></td>
          </tr>
        </tbody>
      </table>

AngularJs Code:

function createTable() {
tableCounter++;
return {
  id: currentTableId++,
  name: `Table ${currentTableId}`,
  columns: [],
  rows: [{}],
  uniqueIdCounter: 1037
}

When creating a new tab, I create a table instance as follows:

   $scope.tables.push(createTable());

$scope.tables = [];
$scope.targetTable = null;

//To add a dynamic column, the following code is used.
$scope.addColumn = function() {
if (tableCounter) {
  var columns = $scope.targetTable.columns,
    id = columns.length;
  $scope.targetTable.columns.push({
    id: columns.length,
    label: `Column ${id}`
   });
  }
};

 //Code snippet for adding a new row
  $scope.addNewRow = function(value, row) {
  if (tableCounter) {
  if (!value || value === "" || typeof value !== 'string') return;
  $scope.targetTable.rows.push({});
   row.id = $scope.targetTable.uniqueIdCounter++;
  }
};

Any valuable inputs? Please share.

Answer №1

I made some minor adjustments to your HTML code without completely overhauling it:

Check out the updated code on JSFiddle: http://jsfiddle.net/0oerpd5u/

     <tbody>
         <tr ng-repeat="r in targetTable.rows">
            <td class="fixed-width" contenteditable="true" ng-model="r.id"></td>
            <td class="fixed-width" contenteditable="true" ng-repeat="column in targetTable.columns" ng-model="r[column.id]" ng-blur="!targetTable.rows[$index+1].id? addNewRow(r[column.id], r): ''"></td>
             <td class="comment-fixed-width" contenteditable="true"  ng-blur="!targetTable.rows[$index+1].id?addNewRow(r.comment, r):''" ng-model="r.comment">></td>
             <td class="blank fixed-width" colspan="2" ng-model="r[column.id]"></td>
         </tr>
     </tbody>

Here are the changes made to your JavaScript code:

  var uniqueIdCounter =1037;
  function createTable() {
    tableCounter++;
    return {
      id: currentTableId++,
      name: `Table ${currentTableId}`,
      columns: [],
      rows: [{id: uniqueIdCounter}],
      uniqueIdCounter: uniqueIdCounter
    }
  }
  $scope.addNewRow = function(value, row) {
    if (tableCounter) {
      if (!value || value === "" || typeof value !== 'string') return;
      $scope.targetTable.rows.push({id :++$scope.targetTable.uniqueIdCounter});
    }
  };

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

Tips for styling cells in a certain column of an ng-repeat table

I am currently facing an issue with a table I have created where the last column is overflowing off the page. Despite being just one line of text, it extends beyond the right edge of the page without being visible or scrollable. The table is built using th ...

Guide on creating a live connection between a slider and a canvas

Currently, I am working on implementing a slider that can dynamically adjust a specific value in the canvas, such as the radius of a circle. Although my code works as intended, I would like the canvas to update in real-time as I move the slider instead of ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

What is the best way to create dynamic transparency based on cursor position?

Is there a way to create an animation like the one on https://meetwalter.com, where the transparency changes with the cursor's position? I previously attempted a similar implementation using CSS, but it seems that the website accomplishes this effect ...

Is there a way to direct to a particular section of an external website without relying on an id attribute in the anchor tag?

I am aware that you can link to specific id attributes by using the following code: <a href="http://www.external-website.com/page#some-id">Link</a> However, what if the external HTML document does not have any ids to target? It seems odd tha ...

Prevent multiple instances of Home screen app on iOS with PWA

There seems to be an issue with the PWA app not functioning properly on iOS devices. Unlike Android, where adding an app to your homescreen will prompt a message saying it's already installed, iOS allows users to add the app multiple times which is no ...

The function addClass() seems to be malfunctioning

I'm currently experimenting with creating a scrolling cursor effect on a string of text. The goal is to make it look like the text has been highlighted with a blinking cursor, similar to what you see in your browser's search bar. window.setInter ...

The dropdown options for the input type file in Vuejs PWA are not appearing

I have created a Vue.js progressive web app that allows users to easily upload images from their mobile phones. While the app typically functions well, there is an issue where upon downloading the app to the homescreen, the image upload feature sometimes b ...

Update the $scope variables with new data fetched from a service

How should I properly update the data retrieved from my service? I am fetching a test array from my dataService and want it to automatically reflect in my view when I call the save() method. Even though I have included the line that is supposed to update m ...

Converting XML data into the JSON format and accurately extracting the relevant values

Currently, I am dealing with an XML object that needs to be converted into JSON format for easier access to values. The structure of the XML object is provided below: <env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'> ...

Ways to speed up the disappearance of error messages

There is a minor issue that I find quite annoying. The validation error message takes too long (approximately 3 seconds) to disappear after a valid input has been entered. Let me give you an example. https://i.sstatic.net/8UKrm.png Do you have any tips o ...

What is the best way to enable autocomplete in AngularJS?

I am working with an object that contains both a name and an ID. I want to implement autocomplete functionality based on the name property. Below is the code snippet that I have tried: //Js file var app=angular.module("myapp",[]); app.controller("controll ...

Get rid of unsafe-eval in the CSP header

I am facing an issue with my old JavaScript code as it is using unsafe-eval. The client has requested to remove unsafe-eval, but the code relies on the eval method in all JavaScript libraries. Removing unsafe-eval breaks the functionality of the code. How ...

Angular is not acknowledging the required fields as specified

I have a question regarding the functionality of my page. Currently, everything is working fine except for the input field for user.productNumber at the bottom. While all the other "required" fields are preventing the "Create Account" button from being e ...

Linkyfy.js does not function correctly with each and not statements

Trying to incorporate a linkifying script on a website, which transforms URLs in text into clickable links. Utilizing the following solution: https://github.com/SoapBox/linkifyjs To make it operational (post-download), the following steps are required: & ...

Adding several JSON values to one item in a Python list

Seeking help with JSON data extraction I have a JSON file with various keys and values, including latitude and longitude coordinates. I am looking to extract these coordinates and store them in a Python list while maintaining their pair. { "url": "ht ...

Debugging Node.js Routes in Visual Studio Code: A Step-by-Step Guide

My application is structured as follows: server.js router routes emails.js index.js In my index.js file, I define the route like this: module.exports = function (app) { app.use('/emails', require('./routes/emails& ...

Not sure about the Fat Arrow (=>) function

Hey there, I've been diving into NextJs and came across this issue: This Module is Functional const GlobalStyles = () => ( <> <Global styles={css` body { color: #000000; } `} ...

Having trouble persisting my login status in Selenium using Python

Has anyone experienced issues with logging into Instagram using an automate tab? Previously, I didn't have any problems, but now it seems that Instagram is not allowing users to log in through automation. An error message stating the following appears ...

What is the best method to initialize a JavaScript function only once on a website that uses AJAX

Currently, I am facing an issue with a javascript function that needs to be contained within the content element rather than in the header. This is due to a dynamic ajax reload process which only refreshes the main content area and not the header section. ...