如何将json数据加载到handsontable中

时间:2016-05-22 10:25:53

标签: javascript angularjs handsontable

我正在使用sheetJs从指令中的csv / xls文件中获取json数据。

myApp.directive("fileRead", [function () {
    return {
        scope: {
            data: '='
        },
        link: function ($scope, $elm, $attrs) {
            $elm.on('change', function (changeEvent) {
                var reader = new FileReader();

                reader.onload = function (evt) {
                    $scope.$apply(function () {
                        var data = evt.target.result;

                        var workbook = XLSX.read(data, {type: 'binary'});

                        var headerNames = XLSX.utils.sheet_to_json(
                                workbook.Sheets[workbook.SheetNames[0]],
                                {header: 1}
                        )[0];

                        console.log("headerNames: ", headerNames);

                        var data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);

                        console.log("sheet2Json: " , data);

                        $scope.columnDefs = [];
                        headerNames.forEach(function (h) {
                            $scope.columnDefs.push({field: h});
                        });

                        $scope.data = data;
                        console.log("file 4: " , data);                             

                        $elm.val(null);
                    });
                };

                reader.readAsBinaryString(changeEvent.target.files[0]);
            });
        }
    };
}]);

以json检索的数据位于$scope.data = data;对象中。我将样本handontable放在一个单独的js文件中,如下所示:

var myData = [
    ["KK", 1234567890, "k.k999@gmail.com", "kvp@gmail.com"],
    ["KK", 1234567890, "k.k999@gmail.com", "kvp@gmail.com"],
    ["KK", 1234567890, "k.k999@gmail.com", "kvp@gmail.com"],
],
        container = document.querySelector('#exampleGrid');

var hot = new Handsontable(container, {
    data: myData,
    startRows: 5,
    startCols: 5,
    minSpareCols: 0,
    //always keep at least 1 spare row at the right
    minSpareRows: 0,
    //always keep at least 1 spare row at the bottom,
    rowHeaders: true,
    colHeaders: ['Name', 'Mobile number', 'Sender Email', 'Receiver Email'],
    contextMenu: true,
    width: 120,
    wordWrap: true
});

查看Handsontable文档,我看到了一个加载json数据的方法:

 hot.loadData(data.data);

现在我如何将scope.data(jsondata)加载到上面的方法中,该方法位于单独的js文件中。我是否必须创建一个控制器并将数据传递给控制器​​范围?

HTML:

<div class="top-big-link">
    <file-read>
        <input id="csvFile" type="file" name="image" accept=".xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" title=" "/>
        <button id="csvFileImport" class="ImportFromExcelButton"><i class="fa fa-file-excel-o"> </i> Import from Excel</button>
    </file-read>
    <script>
        document.getElementById('csvFileImport').addEventListener('click', function () {
            document.getElementById('csvFile').click();

        });
    </script>
</div>

2 个答案:

答案 0 :(得分:1)

我不确定这是否正确,但它对我有用。

通过此链接获得我的解决方案:Passing values from directive to controller

感谢@Thomas Weglinski

解决方案:

将我的指令更改为双向绑定。

Enter date :12-4-2014
12-4-2014   Glenview    21922.22    17

将我的HTML更改为以下内容:

myApp.directive("fileRead", [function () {
    return {
        scope: {
            fromDirectiveFn: '=method'
        },
    },

    function link(scope, element, attrs){

        $scope.data = data; //Json data reecieved from csv/xls file
        $scope.fromDirectiveFn($scope.data);
    }
}

此行<file-read method="loadJson"> <input id="csvFile" type="file" name="image" accept=".xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" title=" "/> <button id="csvFileImport" class="ImportFromExcelButton"><i class="fa fa-file-excel-o"> </i> Import from Excel</button> </file-read> 调用控制器内的函数并传递数据。

答案 1 :(得分:0)

//对于Angular

//内部component.html

<hot-table [settings]="tableSettings" [data]="dataset" licenseKey= 'non-commercial-and-evaluation'></hot-table>

//内部component.ts

tableSettings: any = {
    
    rowHeaders: true,
    // colHeaders: true,
    viewportColumnRenderingOffset: 27,
    viewportRowRenderingOffset: "auto",
    // colWidths: 150,
    // height: 500,
    // allowInsertColumn: false,
    // allowInsertRow: false,
    // allowRemoveColumn: false,
    // allowRemoveRow: false,
    // autoWrapRow: false,
    // autoWrapCol: false,
    // stretchH: "all",
    width: 3000,
    // autoWrapRow: true,
    //height: 487,
    // maxRows: 22,
    // manualRowResize: true,
    // manualColumnResize: true,
    // rowHeaders: true,
    
    colHeaders: [
      "Invoice_No",
      "Product_Description",
      "Receiver_Contact_Person_Name",
      "Receiver_Contact_Number",
      "Dropoff_Address",
      "Dropoff_Area",
      "Dropoff_City",
      "Unit_Price",
      "Number_of_Packages_in_Shipment",
      "Collection_Amount_for_delivered_Product",
      "Payment_Collection_Method",
      "Proof_Of_Delivery",
      "Shipment_Weight",
      "Shipment_Volume",
      "Pickup_Contact_Person_Name",
      "Pickup_Contact_Person_Number",
      "Pickup_Address",
      "Pickup_Area",
      "Pickup_City",
      "Comments"
    ],
    // manualRowMove: true,
    // manualColumnMove: true,
    // contextMenu: true,
    // filters: true,
    // dropdownMenu: true
  };

  dataset = [
    {
      Invoice_No: "ABCD1234",
      Product_Description: "XYZ",
      Receiver_Contact_Person_Name: "Jane Doe",
      Receiver_Contact_Number: "01700000001",
      Dropoff_Address: "DROPOFF_ADDRESS_1",
      Dropoff_Area: "Kawran Bazaar",
      Dropoff_City: "Dhaka",
      Unit_Price: 25,
      Number_of_Packages_in_Shipment: 2,
      Collection_Amount_for_delivered_Product: 50,
      Payment_Collection_Method: "PREPAID",
      Proof_Of_Delivery: "NONE",
      Shipment_Weight: 1,
      Shipment_Volume: 5,
      Pickup_Contact_Person_Name: "John Doe",
      Pickup_Contact_Person_Number: "01700000001",
      Pickup_Address: "PK_Address line",
      Pickup_Area: "Dhanmondi",
      Pickup_City: "Dhaka",
      Comments: "Comment"
    }
  ];
相关问题