How to call export to csv for table data from another template in angularjs?

In the html package I have 2 templates for the header and another for the template. Header template has a button save and download , which is to export the data to a file ngTable csv using the Export ngTable , which is inside the file contents.html template, but it exports only works when I put the anchor tag with the click handlers for export to 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 export the table contents to csv using the button on a separate template.

Update

Incomplete plunker link .. export does not work somehow in plunker

+6
source share
1 answer

The anchor tag in your plunkr is missing ng-href="{{ csv.link() }} , which forces the browser to load csv into a file.

If you must use the button instead of the anchor tag, you can simulate the href function, which 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 since you want the button and table to come from different template files, they are probably associated with different child areas . A quick workaround for this is to tell the export directive to create a csv helper for the 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

+6
source

Source: https://habr.com/ru/post/979279/


All Articles