2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
22 import {FileUtils} from "app/utils";
24 export interface IJsonExportExcelScope extends ng.IScope {
25 initExportExcelData:Function;
29 export class JsonExportExcelDirective implements ng.IDirective {
31 constructor(private fileUtils:FileUtils) {
35 initExportExcelData: '&'//get function that init and returns Models.ExportExcel
38 public restrict = 'E';
40 template = ():string => {
41 return require('./export-json-to-excel.html');
44 private jsonToTableText = (headers:string, dataObj:Array<Object>):string=> {
45 let tableText = headers + "\n";
46 _.each(dataObj, (rowData:any) => {
47 tableText += _.values(rowData).join() + "\n";
52 link = (scope:IJsonExportExcelScope, $elem:any) => {
53 scope.export = ():void => {
54 let exportExcelData = scope.initExportExcelData();
55 exportExcelData.fileName = !!exportExcelData.fileName ? exportExcelData.fileName : 'export-excel';
57 let headers = exportExcelData.tableHeaders.join(",");
59 if (exportExcelData.groupByField) {
60 _.each(_.groupBy(exportExcelData.dataObj, exportExcelData.groupByField), (groupData:Array<Object>) => {
61 tableData += this.jsonToTableText(headers, groupData);
65 tableData = this.jsonToTableText(headers, exportExcelData.dataObj);
68 let blob = new Blob([exportExcelData.metaData.join('\n\n') + '\n\n' + tableData], {type: "text/csv;charset=utf-8"});
70 return this.fileUtils.downloadFile(blob, exportExcelData.fileName + '.csv');
75 public static factory = (fileUtils:FileUtils)=> {
76 return new JsonExportExcelDirective( fileUtils);
81 JsonExportExcelDirective.factory.$inject = ['FileUtils'];