AngularJS自定义更改无法正常工作

时间:2017-05-05 06:46:52

标签: javascript jquery angularjs

我有一个简单的代码,在选择要读取的文件时调用,并弹出带选项的选择框

角色代码 -

angapp.controller('panbulkCtrl', function($scope) {
    $scope.deviceGroups = [];
    $scope.uploadFile = function() {
        var filename = event.target.files[0].name;
        var reader = new FileReader();
        reader.onload = function (e) {
            var rows = e.target.result.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var cells = rows[i].split(",");
                for (var j = 0; j < cells.length; j++) {
                    console.log(cells[j]);
                    $scope.deviceGroups.push(cells[j]);
                }              
            }           
        }
        reader.readAsText(event.target.files[0]);
    }
});

angapp.directive('customOnChange', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var onChangeFunc = scope.$eval(attrs.customOnChange);
            element.bind('change', onChangeFunc);
        }
    };
});

HTML模板

<div class="jumbotron" style="background-color:white">
</div>
<div class="jumbotron container-fluid">
<h3 align="center">PAN Bulk Upload</h3>
</div>
<div class="container">
<div class="row">
<div class="col-lg-9">
<div style="border-right:1px solid #cbc6c6">
<div class="container panel-body">
    <label class="custom-file-upload">
        <input id="fileChoose" type="file" custom-on-change="uploadFile" />
        <i class="fa fa-cloud-upload"> Choose Device Group File</i>
    </label>
    <hr/>
    <select size=5 style="width:200px;height:100px" ng-model="deviceGroupsList" ng-options="o as o for o in deviceGroups">
    </select>
</div>
<div class="container">
    <button ng-click="validateDeviceGroups()">Validate</button>
    <button ng-click="commitDeviceGroups()">Commit</button>
</div>
</div>
</div>
<div class="col-lg-3">
<textarea rows="20" cols="35"></textarea>
</div>
</div>
</div>

uploadFile函数读取并向数组追加文件的行。但是,在单击其他按钮之前,它不会在选择框上正确呈现。我该如何解决?

1 个答案:

答案 0 :(得分:1)

您需要手动运行摘要循环。因为reader.onload函数超出了角度世界。 Angular不会跟踪其中的更改。所以你需要让角度知道某些东西已经超出了它的范围。 Angular需要在UI中更新这些更改。

要做到这一点:

  

$scope.$apply()

将数据追加到数组之后。

因此,您的控制器代码应如下所示:

angapp.controller('panbulkCtrl', function($scope) {
    $scope.deviceGroups = [];
    $scope.uploadFile = function() {
        var filename = event.target.files[0].name;
        var reader = new FileReader();
        reader.onload = function (e) {
            var rows = e.target.result.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var cells = rows[i].split(",");
                for (var j = 0; j < cells.length; j++) {
                    console.log(cells[j]);
                    $scope.deviceGroups.push(cells[j]);
                }              
            }
            $scope.$apply()           
        }
        reader.readAsText(event.target.files[0]);
    }
});