1

I am just wondering if it's possible to have a button to call a different function depending on the page it is in. For example, i have different html pages which displays different data. And i want to have a single button shared among different pages which could download the table shown on the page

PS: I am trying to do this as i thought it could be troublesome if there were alot of pages that display different data and i have to code button in everytime

HTML code of what i am doing now :

            <div class="col-lg-12">
          <div class="page-header">
            <h2 class="displayHeader">Data information for Auditorium</h2>
          </div>
            <form class="form-inline">
              <div class="form-group">
                <label >Search</label>
                <input type="text" ng-model="search" class="form-control" placeholder="Search">
              </div>
            </form>
              <table class="table table-striped table-hover">
                <thead>
                  <tr>
                    <th ng-click="sort('NAME')">Name
                      <span ng-show="sortKey=='NAME'"></span>
                                </th>
                    <th>Block No.
                    </th>
                    <th>Postal Code
                    </th>
                    <th>Street Name
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr dir-paginate="audit in auditoriums|orderBy:sortKey:reverse|filter:search|itemsPerPage:5">
                    <td>{{audit.NAME}}</td>
                    <td>{{audit.ADDRESSBLOCKHOUSENUMBER}}</td>
                    <td>{{audit.ADDRESSPOSTALCODE}}</td>
                    <td>{{audit.ADDRESSSTREETNAME}}</td>
                  </tr>
                </tbody>
              </table>
              <dir-pagination-controls>
                max-size="5"
                direction-links="true"
                boundary-links="true" >
              </dir-pagination-controls>
        </div>
        <div id="tableToCsv">
          <div id="btnDLContainer">
            <button onclick="exportTableToExcel('tableToCsv')" type="button contact-button" class="btnDL">XLSX Download</button>
          </div>

What i have right now is different html pages of code looking like this to download data. So i am thinking if i could place the button in my index page to download the table

Updated ( wrong code just now )

      function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

// Specify file name
filename = filename?filename+'.xlxs':'Excel_Data.xlsx';

// Create download link element
downloadLink = document.createElement("a");

document.body.appendChild(downloadLink);

if(navigator.msSaveOrOpenBlob){
    var blob = new Blob(['\ufeff', tableHTML], {
        type: dataType
    });
    navigator.msSaveOrOpenBlob( blob, filename);
}else{
    // Create a link to the file
    downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

    // Setting the file name
    downloadLink.download = filename;

    //triggering the function
    downloadLink.click();
}
}
6
  • Not enough Info mate show what you tried so far and how the page structure looks like Commented Oct 16, 2018 at 9:17
  • What about having a single page with a single button with a service fetching different data according to some filters? Otherwise, it might be slightly complex to mantain all that. May you please share more informations so that we can better help you? Right now, it's slightly too broad. Commented Oct 16, 2018 at 9:17
  • updated @briosheje Commented Oct 16, 2018 at 9:24
  • @Badgy updated. U guys mind helping me take a look if its possible? And how can i achieve that Commented Oct 16, 2018 at 9:24
  • what is your end goal , to export a specific HTML element enclosed data to csv or any other? Commented Oct 16, 2018 at 9:31

2 Answers 2

1

INDEX.html

<html>
<head>//scripts</head>
<body ng-controller="indexController" ng-app="myApp">
<button ng-click=download()>Download</button>
<div ng-view>//let's take you have you child pages here with child controller</div>
</body>
</html>

IndexController

    angular.module('myApp'[]).controller("indexController",function(dataservice)){
$scope.download(){
      JSONToCSVConvertor(dataservice.getTable());
}

//jsfiddle.net/hybrid13i/JXrwM/

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
    //If JSONData is not an object then JSON.parse will parse the JSON string 
     in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : 
    JSONData;

    var CSV = '';    
    //Set Report title in first row or line

    CSV += ReportTitle + '\r\n\n';

    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";

        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {

            //Now convert each value to string and comma-seprated
            row += index + ',';
        }

        row = row.slice(0, -1);

        //append Label row with line break
        CSV += row + '\r\n';
    }

    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var row = "";

        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }

        row.slice(0, row.length - 1);

        //add a line break after each row
        CSV += row + '\r\n';
    }

    if (CSV == '') {        
        alert("Invalid data");
        return;
    }   

    //Generate a file name
    var fileName = "MyReport_";
    //this will remove the blank-spaces from the title and replace it with an underscore
    fileName += ReportTitle.replace(/ /g,"_");   

    //Initialize file format you want csv or xls
    var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

    // Now the little tricky part.
    // you can use either>> window.open(uri);
    // but this will not work in some browsers
    // or you will not get the correct file extension    

    //this trick will generate a temp <a /> tag
    var link = document.createElement("a");    
    link.href = uri;

    //set the visibility hidden so it will not effect on your web-layout
    link.style = "visibility:hidden";
    link.download = fileName + ".csv";

    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    }
}

ChildController

app.controller("childController",function(dataService){
//let's say you get your data from rest calls here like this
    $http('getData').then(function(response){
    $scope.auditorium = response.data;    
    dataService.setTable($scope.auditorium);
})
})

dataService:

app.service('dataServcice',function(){
var tabledata=[];
return{
setTable:function(data){
          tabledata=data;
          }
}
getTable:function(){
         return tabledata;
         }
})

In the same manner which ever page you load you should only set the data in service at load time of the controller and when you will click the download button it will get downloaded as CSV file.

Sign up to request clarification or add additional context in comments.

1 Comment

Alright, i'll give this a try tmr. I just knocked off work haha. Thanks for the help!
0

Yes you can do this. Create a directive or component having a button in it's template and create an attribute scope variable specific to the page in which you can pass the page specific data to the directive like if you want to download the table you can make a variable which will take data of table and in directives link function write the logic to download the table.

1 Comment

Do you have a link or something where i can learn more about that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.