user2925894
user2925894

Reputation: 259

My scope variable won't update in the html view

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.

Upvotes: 1

Views: 568

Answers (2)

Busata
Busata

Reputation: 1118

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?

Upvotes: 1

karaxuna
karaxuna

Reputation: 26930

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);
     }
  });
};

Upvotes: 1

Related Questions