̶$̶s̶c̶o̶p̶e̶.̶s̶e̶l̶e̶c̶t̶F̶i̶l̶e̶F̶o̶r̶U̶p̶o̶a̶d̶(̶)̶{̶
$scope.selectFileForUpload = function(files) {
$scope.SelectFileForUpload = files[0];
}
坦率地说,函数名和变量名的大小写不同是不好的编程实践。这使得代码容易出错,而且很难阅读。
而不是使用
angular.element(this).scope()
,我建议使用与
ng-model controller
:
app.directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
用法:
<input type="file" name="file" accept="image/*"
̶o̶n̶c̶h̶a̶n̶g̶e̶=̶"̶a̶n̶g̶u̶l̶a̶r̶.̶e̶l̶e̶m̶e̶n̶t̶(̶t̶h̶i̶s̶)̶.̶s̶c̶o̶p̶e̶(̶)̶.̶s̶e̶l̶e̶c̶t̶F̶i̶l̶e̶F̶o̶r̶U̶p̶l̶o̶a̶d̶(̶t̶h̶i̶s̶.̶f̶i̶l̶e̶s̶)̶"̶
select-ng-files ng-model="files"
ng-change="selectFileForUpload(files)"
class="form-control input-bordered" required>
这个
.scope()
方法
angular.element
要求
Debug Data
要启用。这与AngularJS的小型版本不同。
此外,使用
onchange
属性未与AngularJS执行上下文及其摘要循环集成。只有在AngularJS执行上下文中应用的操作才能受益于AngularJS数据绑定、异常处理、属性监视等。
有关详细信息,请参见
ng-model for
<input type=âfileâ/>
(with directive DEMO)