AngularJS中使用jsPDF导出根表格时如何排除子表格
Hey there! Let's figure out how to exclude child tables when exporting your #table1 with jsPDF in AngularJS—no jQuery required. Here are two straightforward approaches you can use:
1. Temporary Hide Child Tables (Then Restore)
This method hides the child tables right before export, then brings them back once the PDF is generated. It’s simple and doesn’t mess with your original DOM structure long-term.
First, make sure your child tables have a consistent class (like .child-table) so you can target them easily. Then update your controller function:
$scope.exportToPdf = function(tableId) { // Target the main table and its child tables using AngularJS's jqLite const mainTable = angular.element(`#${tableId}`); const childTables = mainTable.find('.child-table'); // Save each child table's original display state const originalDisplayStates = []; childTables.each(function() { originalDisplayStates.push(this.style.display); angular.element(this).css('display', 'none'); // Hide temporarily }); // Run your jsPDF export logic const doc = new jsPDF(); doc.autoTable({ html: `#${tableId}` }); doc.save('table-export.pdf'); // Restore each child table's original display state childTables.each(function(index) { angular.element(this).css('display', originalDisplayStates[index]); }); };
2. Clone the Main Table (Remove Child Tables Before Export)
If you don’t want to modify the original DOM at all, clone the main table, strip out the child tables, and export the cloned version instead. This keeps your live UI unaffected during the export process.
$scope.exportToPdf = function(tableId) { const mainTable = angular.element(`#${tableId}`); // Create a deep clone of the main table const clonedTable = mainTable.clone(true); // Remove all child tables from the cloned copy clonedTable.find('.child-table').remove(); // Create a temporary container to hold the cloned table (required for jsPDF) const tempContainer = angular.element('<div></div>'); tempContainer.append(clonedTable); angular.element(document.body).append(tempContainer); // Export the cleaned-up cloned table const doc = new jsPDF(); doc.autoTable({ html: tempContainer[0].firstElementChild }); doc.save('table-export.pdf'); // Clean up the temporary container tempContainer.remove(); };
Key Notes
- Replace
.child-tablewith the actual class (or a comma-separated list of IDs) that identifies your child tables. - Both methods use AngularJS’s built-in jqLite (no full jQuery dependency), which fits perfectly with your AngularJS setup.
内容的提问来源于stack exchange,提问作者Basma Radadi

