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