In a html body I have 2 templates one for header and other for template. Header template has a save and download
button which is supposed to export a ngTable data to a csv file using ngTable Export, which is inside a contents.html template file, but this export only works when I place an anchor tag with click handler to export in the same template.
content.html (template 1)
<a class="btn btn-default export-btn" ng-click='csv.generate($event, "report.csv")' href=''>Export</a> <!-- this works -->
<table ng-table="tableParams" show-filter="true" class="table" export-csv="csv">
<tr ng-repeat="item in $data" height="10px" class="animate" ng-animate="{enter: 'animate-enter', leave: 'animate-leave'}">
<td data-title="'Date'" align="center" filter="{ 'date': 'text' }" sortable="'date'">{{ item.date | date: 'd MMM yyyy' }}</td>
<td data-title="'Label'" align="center" filter="{ 'label': 'text' }" sortable="'label'">{{item.label}}</td>
<td data-title="'Count'" align="center" filter="{ 'count': 'text' }" sortable="'count'">{{item.count}}</td>
</tr>
</table>
header.html (template 2)
<button class="save-button" ng-click='csv.generate($event, "report.csv")'></button> <!-- does not work-->
Please help me in exporting table content to csv with a button on a separate template.
Update
Unfinished plunker link.. export not working somehow in plunker
The anchor tag in your plunkr is missing ng-href="{{ csv.link() }}
, which is what causes the browser to download the csv as a file.
If you must use a button instead of an anchor tag, you can simulate href
with a function that calls csv.generate
, and then sets location.href
to the value returned by csv.link()
:
$scope.exportFile = function($event, fileName) {
$scope.csv.generate($event, "report.csv");
location.href=$scope.csv.link();
};
But, because you want the button and table to come from different templates files, they are probably being bound to different child scopes. A quick workaround for this is to tell the export directive to create the csv
helper on an object that exists in the $parent
scope:
<table ng-table="tableParams" export-csv="helper.csv">
Then change your controller to:
$scope.helper = {
csv: null //will be replaced by the export directive
};
$scope.exportFile = function($event, fileName) {
$scope.helper.csv.generate($event, "report.csv");
location.href=$scope.helper.csv.link();
};
Here is a working demo: http://plnkr.co/edit/a05yJZC1pkwggFUxWuEM?p=preview