2017-05-05 182 views
3

我有一個是在選擇一個文件,通過它來讀取和popluate的選項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

您需要手動運行摘要循環。因爲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]); 
    } 
});