我的作用域变量没有在html视图中更新

My scope variable won't update in the html view

本文关键字:html 视图 更新 作用域 变量 我的      更新时间:2023-09-26

下面是我的angularjs代码:

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

下面是html代码:

<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>

我正试着列出所有的文件。但是$scope。附件变量不会更新,我可以在控制台日志中看到附件。长度可以是1和2等等,但在页面上它总是0

工作活塞kr: 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]);
      }
    })
  };
})

原始讨论:AngularJs:如何检查文件输入字段的变化?

美元范围。$apply因为onchange事件而被使用。但是,不确定为什么ng-change在这种情况下不起作用?

试试:

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