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 * as _ from "lodash";
23 import {FileUtils} from "app/utils";
25 export interface IJsonExportExcelScope extends ng.IScope {
26 initExportExcelData:Function;
30 export class JsonExportExcelDirective implements ng.IDirective {
32 constructor(private fileUtils:FileUtils) {
36 initExportExcelData: '&'//get function that init and returns Models.ExportExcel
39 public restrict = 'E';
41 template = ():string => {
42 return require('./export-json-to-excel.html');
45 private jsonToTableText = (headers:string, dataObj:Array<Object>):string=> {
46 let tableText = headers + "\n";
47 _.each(dataObj, (rowData:any) => {
48 tableText += _.values(rowData).join() + "\n";
53 link = (scope:IJsonExportExcelScope, $elem:any) => {
54 scope.export = ():void => {
55 let exportExcelData = scope.initExportExcelData();
56 exportExcelData.fileName = !!exportExcelData.fileName ? exportExcelData.fileName : 'export-excel';
58 let headers = exportExcelData.tableHeaders.join(",");
60 if (exportExcelData.groupByField) {
61 _.each(_.groupBy(exportExcelData.dataObj, exportExcelData.groupByField), (groupData:Array<Object>) => {
62 tableData += this.jsonToTableText(headers, groupData);
66 tableData = this.jsonToTableText(headers, exportExcelData.dataObj);
69 let blob = new Blob([exportExcelData.metaData.join('\n\n') + '\n\n' + tableData], {type: "text/csv;charset=utf-8"});
71 return this.fileUtils.downloadFile(blob, exportExcelData.fileName + '.csv');
76 public static factory = (fileUtils:FileUtils)=> {
77 return new JsonExportExcelDirective( fileUtils);
82 JsonExportExcelDirective.factory.$inject = ['FileUtils'];