【问题标题】:My scope variable won't update in the html view我的范围变量不会在 html 视图中更新
【发布时间】:2014-03-18 20:17:31
【问题描述】:

这是我的 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.attachments 变量不会更新,我可以在控制台日志中看到 attachments.length 得到 1 和 2 等等,但在页面上它始终是 0。

【问题讨论】:

    标签: javascript html angularjs angularjs-scope


    【解决方案1】:

    工作小伙伴: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: How to check for changes in file input fields?

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

    【讨论】:

      【解决方案2】:

      试试这样:

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

      【讨论】:

      • 为了更清楚起见,这里需要使用$apply,因为由于使用了 onchange 属性,$scope 会在 Angular 的上下文之外进行更改。
      • 谢谢,这个答案有效。并感谢您的解释 ivarni
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多