javascript - 我的范围变量不会在 html View 中更新

标签 javascript html angularjs angularjs-scope

这是我的 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。

最佳答案

工作插件: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 在这种情况下不起作用?

关于javascript - 我的范围变量不会在 html View 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22478186/

相关文章:

javascript - 如何设置共享同一类的元素的样式

css - 使用单个 Controller 控制两个 Partials 时不加载 Angular css 文件

javascript - Angular Controller - 他们为什么将其命名为 Controller ?

html - 为什么在浏览器中缩放时只有字体大小增加?

javascript - 将控件从容器中拖放到 Canvas 上

javascript - Lodash 适用于两个对象,但如果具有三个对象则返回 null

javascript - Backbone.js - 自定义从 "fetch()"返回的数据的组织

javascript - 提交无法发送textarea的数据

javascript - 将 php 数组转换为 javascript 数组

javascript - 找不到类型为 '[object Object]' 的不同支持对象 'object' ,但它已经是一个数组