【问题标题】:JavaScript/ AngularJS: Error Message displays only when I click twice the buttonJavaScript / AngularJS:仅当我单击两次按钮时才显示错误消息
【发布时间】:2020-05-20 21:43:03
【问题描述】:

我有一个 angularJS 视图,允许用户上传 Excel 数据并将其导入 SQL 服务器表。

我添加了数据的客户端验证,但只有当我再次单击上传/导入按钮时才会显示错误消息。我不确定我的代码中的哪个部分导致了这个问题。

是否可以寻求帮助以尝试解决此问题? 我想我可能需要移动 $scope.Message 变量的赋值位置,但是在哪里?

我包括 Javascript/angularjs 代码和 html 视图。

AngularJS

//Parse Excel Data   
$scope.ParseExcelDataAndSave = function () {

    var file = $scope.SelectedFileForUpload;

    if (file) {

        var reader = new FileReader();

        reader.onload = function (e) {

            var filename = file.name;
            // pre-process data
            var binary = "";
            var bytes = new Uint8Array(e.target.result);
            var length = bytes.byteLength;

            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }

            // call 'xlsx' to read the file
            var data = e.target.result;
            var workbook = XLSX.read(binary, { type: 'binary', cellDates: true, cellStyles: true });
            var sheetName = workbook.SheetNames[0];
            var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

            exceljsonObj = excelData;

            var errors = [];
            var rowCounter = 1;

            for (var j = 0; j < exceljsonObj.length; j++) {

                var xdata = exceljsonObj[j];

                if (xdata['Meeting ID'] === undefined || xdata['MeetingID'] === undefined) {

                    errors.push('Row: ' + rowCounter + ' is missing the Meeting ID value.' +
                                ' Please, verify that the data you are trying to upload meets the required criteria, ' +
                                'and then try to upload your file again.');
                }

                else if ((xdata['Legistar Id'].toUpperCase() === undefined || xdata['LegistarID'].toUpperCase() === undefined) &
                    (xdata['Agenda Item'].toUpperCase() === undefined ||xdata['AgendaItem'].toUpperCase() === undefined)) {

                    errors.push('Row: ' + rowCounter + ' Meeting has no Legistar ID and no Agenda Item. Please check data.');                        
                }
                rowCounter++;
            }

            if (errors.length > 0) {
                $scope.Message = 'Please, verify that the file you are trying to upload is correctly formatted, \n ' +
                                    'and that the data it contains, meets the expected criteria, then click the upload button again. \n Thank you!'
            }
            else {

                // Save data   
                $scope.SaveData(excelData);
            }
        };
    }

    reader.onerror = function (ex) {
        console.log(ex);
    };

    reader.readAsArrayBuffer(file);
};

HTML 视图

<body ng-app="MyApp">
    <div class="container py-4" ng-controller="MyController">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5>Cross Reference List</h5>
            </div>
            <div class="card-body">

                @* Upload Button *@
                <button style="margin-bottom:10px;" type="button" class="btn btn-primary rounded-0" data-toggle="modal" data-target="#myModal">
                    <i class="far fa-file-excel"></i> Upload Excel File
                </button>



                @* Modal Window *@
                <div class="modal" id="myModal">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">Upload Cross-Reference List</h4>
                                <button type="button" class="close" data-dismiss="modal">×</button>
                            </div>
                            <div class="modal-body">
                                <div class="col-md-12">
                                    <div class="input-group">
                                        <div class="custom-file">
                                            <input type="file" name="file" class="custom-file-input" onchange="angular.element(this).scope().UploadFile(this.files)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
                                            <label class="custom-file-label" for="inputGroupFile04">Choose file</label>
                                        </div>
                                        <div class="input-group-append">
                                            <button class="btn btn-outline-secondary" ng-disabled="!SelectedFileForUpload" ng-click="ParseExcelDataAndSave()" /><i class="fa fa-upload"></i> Upload
                                        </div>
                                    </div>
                                    <span class="text-success">
                                        {{Message}}
                                    </span>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal" ng-click="clearText()" />Close
                            </div>
                        </div>
                    </div>
                </div>      

                @* Main Table *@
                <table id="dataTable" class="table table-bordered table-striped" ;>
                    <thead>
                        <tr>
                            <th style="width: 90px;">Meeting ID</th>
                            <th style="width: 105px;">Agenda Item</th>
                            <th style="width: 85px;">Legistar ID</th>
                            <th>Title</th>
                        </tr>
                    </thead>
                </table>

            </div>
        </div>
    </div>
</body>

【问题讨论】:

  • 在分配 $scope.Message 后尝试添加 $scope.$apply()
  • 同意@tbone849,这可能是范围摘要问题。作为一个小技巧,您可以尝试使用 $timeout 服务在下一个摘要周期中获取它$timeout(function () { $scope.Message = 'Please, verify that the file you are trying to upload is correctly formatted, \n ' + 'and that the data it contains, meets the expected criteria, then click the upload button again. \n Thank you!' }, 100)
  • 您好,感谢您的推荐。我将尝试每一个,看看是否有效,我希望它有效。完成后我会立即通知您,并向您展示我如何应用这个想法。再次感谢您。
  • @tbone849,我只是添加 $scope.$apply() 还是必须将消息包装在匿名函数中?我不确定如何使用它。谢谢。
  • 你也可以。要么立即添加,要么包装。两者都可以。

标签: javascript html angularjs dom-events import-from-excel


【解决方案1】:

$scope 摘要问题。分配 $scope.Message 后调用 $scope.apply()

if (errors.length > 0) {
            $scope.Message = 'Please, verify that the file you are trying to upload is correctly formatted, \n ' +
                                'and that the data it contains, meets the expected criteria, then click the upload button again. \n Thank you!'

    $scope.$apply();
 }

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 2017-10-04
    • 2022-10-24
    • 2023-03-22
    • 1970-01-01
    • 2017-02-14
    • 2022-11-23
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多