What is the best way to convert a table string into an HTML table using AngularJS?

I'm currently working on converting a table string (such as csv) into an HTML table. While my code functions well with simpler tables, it encounters issues when dealing with merged rows and columns. Could anyone guide me on how to incorporate rowspan and colspan within the script?

<!DOCTYPE html>
<html ng-app="" ng-controller="myCtrl">
<style>
table, th, td {
border: 1px solid black;
padding:5px;
}
table {
   border-collapse: collapse;
   margin:10px;
}
</style>
<body>
<button ng-click="processData(allText)">
    Display CSV as Data Table
</button>
<div id="divID">
    <table>
        <tr ng-repeat="x in data">
            <td ng-repeat="y in x">{{ y }}</td>
        </tr>
    </table>
</div>
<div>
    <table>
    </table>
</div>

<script>
function myCtrl($scope, $http) {

$scope.allText=" |Through Air |Over Surface |\nRS(0)|in. CM(1)|mm CM(1)|in. CM(2)|mm CM(2)|\nB |3/32\n (a) CM(1)|2.4 \n (a) CM(1)|3/32 \n (a) CM(2)|2.4 \n (a) CM(2)|\nD |1/16\n (a) CM(1)|1.6 \n (a) CM(1)|1/8 \n (a) CM(2)|3.2 \n (a) CM(2)|\nLAST ROW";
$scope.processData = function(allText) {
    // split content based on new line
    var allTextLines = allText.split(/\|\n|\r\n/);
    var headers = allTextLines[0].split('|');
    var lines = [];

    for ( var i = 0; i < allTextLines.length; i++) {
        // split content based on comma
        var data = allTextLines[i].split('|');
        if (data.length == headers.length) {
            var temp = [];
            for ( var j = 0; j < headers.length; j++) {
                temp.push(data[j]);
            }
            lines.push(temp);
        }
    };
    $scope.data = lines;
};
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

| ---is the delimiter for cell

|\n ---for new line

RS(#) ---Row Span w.r.t column number

CM(#) ---Column split w.r.t column header

The value in $scope.allText represents a CSV table string, and the expected output should resemble this table - https://i.sstatic.net/o0Scf.jpg

Answer №1

Within the processData function, it is recommended to structure the datum representing a table cell as an object with properties such as rowSpan and columnSplit:

[[{value: 10, rowSpan: 1, columnSplit: 0}, ... ] ... ]

The provided data in the example appears to have some issues as it treats headers spanning two columns as one 'column', while the other columns are considered split columns. To address this issue, you may need to increment each rowSpan value by 1:

<td ng-repeat="y in x" rowSpan="{{y.rowSpan + 1 }}">{{ y.value }}</td>

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

position the cursor at the end of the text within the text box

I am looking to move the cursor to the end of the text inside a text box that already contains text. Is there a way to achieve this using Java Script, CSS, or JQuery? <span> <input id="listInput" class="autocomplete-input singleselect-autocom ...

My Ruby on Rails app seems to be malfunctioning in a major way

Instead of sharing code snippets, I’ve encountered difficulties in getting my jQuery code to work correctly. If you're curious, you can view the issues on Stack Overflow: Why doesn’t this jQuery code work? and This jQuery hide function just does n ...

Check if the value is a string and contains a floating point number; if so, parse and format the float

I need to work on formatting decimal values returned by an API that only responds with strings. The requirement is to add a leading zero but no trailing zeros to any decimal value in the string. If the value is not a float, it should remain unchanged. For ...

Sending parameters within ajax success function

To streamline the code, I started by initializing the variables for the selectors outside and then creating a function to use them. Everything was working fine with the uninitialized selector, but as soon as I switched to using the variables, it stopped wo ...

Nodejs and express authentication feature enables users to securely access their accounts by verifying their identity before they

I am currently working on a straightforward registration page that needs to save user input (name, email, password) into a database. My tools for this task are express and node. What I am experimenting with is consolidating all the database operations (suc ...

The reduce function doesn't return a value in JavaScript

const items = [ { item: 'apple', cost: 2 }, { item: 'orange', cost: 4 }, { item: 'pear', cost: ' ' }, { item: 'grape', cost: 6 }, { item: 'watermelon', cost: 8 }, { item: 'kiwi', cost: & ...

Mapping an object in a table only results in the final value being displayed

I am facing an issue with my data object containing an array of data that I have mapped inside a table. The problem arises when I try to retrieve the id value of any item in the table's rows using console.log(). It always returns the id of the last it ...

Parsing JSON data as files are being read in an asynchronous manner

I have a task of reading multiple JSON files and consolidating their data into a single array. Here is my approach: const files = ['file0.json', 'file1.json', 'file2.json', 'file3.json'] To achieve this, I utilize ...

Trying to get a jQuery click function to trigger only once in CoffeeScript code

I've been searching high and low for a solution but nothing seems to be working. The issue I'm encountering is that I have a function that is supposed to post content to either a Facebook wall or a Twitter feed, but the click function only seems ...

Using HTML5 and an ASP.NET web method to allow for file uploads

My attempt to upload a file to the server using an HTML5 input control with type="file" is not working as expected. Below is the client-side JavaScript code I am using: var fd = new FormData(); fd.append("fileToUpload", document.getElementById(&ap ...

How to automatically refresh a page in AngularJS after a POST request

After making a POST request, I attempted to use $state.reload in my controller to refresh the page. However, it is not updating the data on my page after registering the form. I have to manually refresh the page to see the correct data. .controller(' ...

The div block containing the table is experiencing horizontal overlap as additional elements are inserted

When creating a table within the div section of the code, I am incorporating text using the DRAG and DROP feature with appropriate styling. The table adjusts in size when I resize my window, indicating that it is functioning correctly. However, as the num ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Manipulate object position using Aframe and three.js

I'm working on developing a game using A-frame. I'm trying to add a shooting effect by incorporating a gun model that follows the user's cursor. I've coded a click event so that an object moves in front of the gun and follows the direct ...

The communication between a Firefox XUL extension and a webpage

Currently developing a Firefox XUL extension and in need of incorporating interaction between the web page and the extension. For instance, whenever a link is clicked on the page, I would like to trigger a function within the XUL extension. Is there any k ...

Detect issues using AngularJS and Restangular

I'm struggling with this code snippet: MyService.one($routeParams.wuid).doGET('test').then(function(e){ alert('ok'); }, function errorCallback(response){ alert('error'); }); When calling the API I set up ...

Protractor is unable to locate the password input field on Gmail using its ID

Currently, I am in the process of configuring Protractor to test my application. However, I am encountering a roadblock as it requires authentication through Gmail and I am struggling with the login process: describe('Vivace Home page', function ...

Tutorial on wrapping HTML content in a CDATA tag using jQuery

Is there a way to enclose some HTML in an element using a CDATA tag to "sterilize" it, so to speak? I've attempted to do so using the following code: $(this).html( "<![CDATA[" + $(this).html() + "]]>" ); However, this approach simply encodes ...

Are trailing commas or missing keys acceptable in JavaScript object notation?

I have created a code generator and I am contemplating whether or not to address the issue of the extra comma at the end. While Internet Explorer seems to ignore it, I want to ensure cross-browser compatibility and generate valid code. function init() { v ...

Transmitting a custom PDF document through email with React and Node.js

Currently, I am in the process of developing an application designed to streamline the completion of a complex form. The data entered into this form will be stored on a remote database for future reference and editing purposes. Once the form is ready for s ...