Angularjs按钮根据页面具有不同的功能

时间:2018-10-16 09:12:52

标签: javascript angularjs

我只是想知道是否可以有一个按钮来调用不同的函数,具体取决于它所在的页面。例如,我有不同的html页面,它们显示不同的数据。而且我希望在不同页面之间共享一个按钮,可以下载页面上显示的表格

PS:我正在尝试执行此操作,因为我认为如果有很多页面显示不同的数据并且我每次都必须编码按钮会很麻烦

我现在正在做的HTML代码:

            <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>

我现在拥有的是不同的HTML页面,看起来像这样下载数据。所以我在想是否可以将按钮放在索引页面中以下载表格

已更新(刚才错误的代码)

      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();
}
}

2 个答案:

答案 0 :(得分: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;
         }
})

以相同的方式加载页面,仅应在控制器加载时将数据设置为可用,然后单击下载按钮,数据将以CSV文件的形式下载。

答案 1 :(得分:0)

是的,您可以这样做。 创建在模板中具有按钮的指令或组件,并创建特定于页面的属性范围变量,您可以在其中将页面特定的数据传递给指令,例如,如果您要下载表,则可以创建将接收数据的变量of table和in指令中的链接函数编写下载表的逻辑。