2014-09-03 19 views
0

我對AngularJs有一個有趣的問題。我正在嘗試創建一個圖像文件的動態列表,用戶可以在他/她提交之前將其添加到數組中。我想用ng-repeat在列表中顯示添加的文件名稱。AngularJs:將輸入選定文件添加到數組中,並在ng-repeat指令中顯示文件名稱

<h5>Images</h5>           
<ul> 
    <li data-ng-repeat="image in images"> 
     {{image.name}} 
    </li> 
</ul> 
<button type="button" data-ng-click="addImage()">ADD IMAGE</button> 

基本上,用戶點擊「添加圖像」按鈕上方和文件選擇對話框會出現。一旦用戶選擇了一個文件,細節就被添加到數組中。這一切工作正常......但是,ng-repeat指令沒有更新。爲什麼會這樣?

app.controller('ImagesController', ['$scope', function($scope) { 
    $scope.init = function() { 
     $scope.images = []; 
    }; 
    $scope.init(); 

    $scope.addImage = function() { 
     input = document.createElement('input'); 
     input.type = "file"; 
     input.onchange = function() { 
      $scope.images.push({ 
       name: input.value.split(/(\\|\/)/g).pop(), 
       file: input.files[0] 
      }); 
     }; 
     setTimeout(function(){ 
      $(input).click(); 
     }, 200);   
    }; 
}]); 

回答

3

此回調發生在Angular應用程序的範圍之外。

嘗試添加$scope.$apply();後,您將新值手動觸發摘要。有時候有更好的方法可以做到這一點,但這至少會證明這是問題所在。

input.onchange = function() { 
    $scope.images.push({ 
    name: input.value.split(/(\\|\/)/g).pop(), 
    file: input.files[0] 
    }); 
    $scope.$apply() 
}; 
+0

你是對的。我知道這與範圍有關。 – Hegemon 2014-09-03 18:43:13

相關問題