Skip to content

Added support for csv-headers returned from promise resolution. #219

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ ngCsv attributes
----------------
* ng-csv: The data array - Could be an expression, a value or a promise.
* filename: The filename that will be stored on the user's computer
* csv-header: If provided, would use this attribute to create a header row
* csv-header: If provided, would use this attribute to create a header row. Could be an expression, a value or a promise.

```html
<button type="button" ng-csv="getArray" csv-header="['Field A', 'Field B', 'Field C']" filename="test.csv">Export</button>
Expand Down
28 changes: 21 additions & 7 deletions src/ng-csv/services/csv-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,28 @@ angular.module('ngCsv.services').
var csv = "";
var csvContent = "";

var dataPromise = $q.when(data).then(function (responseData) {
var csvResolvables = [data];
if (angular.isDefined(options.header) && options.header) {
csvResolvables.push(options.header);
}

var dataPromise = $q.all(csvResolvables).then(function (responseDataAll) {
//responseData = angular.copy(responseData);//moved to row creation
// Check if there's a provided header array
if (angular.isDefined(options.header) && options.header) {
if (angular.isDefined(responseDataAll[1]) && responseDataAll[1]) {
var encodingArray, headerString;

var headerData = [];

if (angular.isArray(responseDataAll[1])) {
headerData = responseDataAll[1];
}
else if (angular.isFunction(responseDataAll[1])) {
headerData = responseDataAll[1]();
}

encodingArray = [];
angular.forEach(options.header, function (title, key) {
angular.forEach(headerData, function (title, key) {
this.push(that.stringifyField(title, options));
}, encodingArray);

Expand All @@ -89,11 +103,11 @@ angular.module('ngCsv.services').

var arrData = [];

if (angular.isArray(responseData)) {
arrData = responseData;
if (angular.isArray(responseDataAll[0])) {
arrData = responseDataAll[0];
}
else if (angular.isFunction(responseData)) {
arrData = responseData();
else if (angular.isFunction(responseDataAll[0])) {
arrData = responseDataAll[0]();
}

// Check if using keys as labels
Expand Down