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

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

最佳答案

索引.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>

索引 Controller

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

子 Controller

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

数据服务:

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

以与加载任何页面相同的方式,您应该只在 Controller 加载时设置服务中的数据,当您单击下载按钮时,它将下载为 CSV 文件。

关于javascript - Angularjs按钮根据页面具有不同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52831946/

相关文章:

php - 使用 PHP 通过 JavaScript 编写 HTML

Angularjs : sorting shows different result in chrome and firefox browser

javascript - 使用 javaScript 或 jquery 清除页面刷新缓存

javascript - AngularJS 如何使用过滤器延迟加载图像

javascript - Google map - 多个 InfoWindows

javascript - 为什么我的文本不是 h3?

javascript - 从客户端设置和清除 Node 服务器上的超时

javascript - 使用工厂在 Controller 之间共享信息

javascript - AngularJs - 想要在 ng-repeat 的基础上更改按钮的文本

javascript - VueJs 将 bool 值绑定(bind)到下拉列表