简体   繁体   中英

How can I parse my table string into html table in angular JS?

I'm trying to convert table string (like csv) to html table. My code works fine with simple table but when it merged row and column it fails. so how do i can use rowspan and column span in 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 dilimiter for cell

|\\n ---for new line

RS(#) ---Row Span wrt column number

CM(#) ---Column split wrt column header

and value in $scope.allText is CSV table string

so essentially i should get this table as output- 输出表

In your processData function, make the datum that represents a table cell an object with rowSpan and columnSplit properties:

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

The data you have in your example seems to be problematic because it seems to define those headers that span two columns as one 'column', and the other columns are actually a split column. So I suppose in your case, you'd have to add 1 to every rowSpan:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM