1

Here is my angularjs code:

$scope.attachments = [];

$scope.uploadFile = function(files){
   for(var i=0; i<files.length; i++){
     $scope.attachments.push(files[i]);
     console.log($scope.attachments.length);
   }
};        

Here is the html code:

<input multiple ng-class="{true:'btn btn-success', false:'btn btn-danger'
[fileUploadedStatus]" style="width:15em" type="file" name="file"
onchange="angular.element(this).scope().uploadFile(this.files)"/>


    {{attachments.length}}
    <ul>
        <li ng-repeat="attachment in attachments">
            attachment: {{attachment.name}}
        </li>
    </ul>

I am trying to list out all the files. But the $scope.attachments variable won't update, i can see in the console log the attachments.length get's 1 and 2 and so on, but on the page it's always 0.

user2925894
  • 259
  • 2
  • 5
  • 17

2 Answers2

1

Try like this:

$scope.uploadFile = function(files){
  $scope.$apply(function(){
     for(var i=0; i<files.length; i++){
        $scope.attachments.push(files[i]);
        console.log($scope.attachments.length);
     }
  });
};
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • And for added clarity, `$apply` needs to be used here because the `$scope` is being changed outside of angular's context due to the use of the onchange property. – ivarni Mar 18 '14 at 12:14
  • Refer to the discussion: http://stackoverflow.com/questions/17922557/angularjs-how-to-check-for-changes-in-file-input-fields – Busata Mar 18 '14 at 12:15
  • Thanks, this answer works. And thanks for the expplaination ivarni – user2925894 Mar 18 '14 at 12:38
1

Working plunkr: http://plnkr.co/edit/mrL1SgMV7DTEEdBg54Rm?p=preview

HTML:

  <br/>Attachments: {{attachments.length}} {{dummy}}
  <ul>
    <li ng-repeat="attachment in attachments">
      attachment: {{attachment.name}}
    </li>
  </ul>
</body>

JS:

angular.module('app', []).controller('AppCtrl', function($scope) {
  $scope.attachments = [];

  $scope.uploadFile = function(element) {
    $scope.$apply(function(scope) {
      for (var i = 0; i < element.files.length; i++) {
        scope.attachments.push(element.files[i]);
      }
    })
  };

})

Original discussion: AngularJs: How to check for changes in file input fields?

$scope.$apply used because of the onchange event. However, not really sure why ng-change doesn't work in this case?

Community
  • 1
  • 1
Busata
  • 1,088
  • 1
  • 10
  • 24