我正在尝试使用angularjs在asp.net mvc中上传文件。我的文件上传用户界面如下。
<form name="f1" class="form-horizontal" ng-submit="SaveFile()" novalidate>
<div style="color: red">{{Message}}</div>
<div class="col-md-12">
<label>Select File:</label>
<input type="file" name="file" accept="image/*"
onchange="angular.element(this).scope().selectFileForUpload(this.files)"
class="form-control input-bordered" required>
<span class="text-danger" ng-show="(f1.file.$dirty || IsFormSubmitted) && f1.file.$error.required">Image required!</span>
<span class="text-danger">{{ FileInvalidMessage }}</span>
</div>
<div class="col-md-12">
<label>Description:</label>
<input type="text" name="uFileDescription" class="form-control input-bordered {{(IsFormSubmitted?'ng-dirty' + (f1.uFileDescription.$invalid?' ng-invalid' : ''):'')}}" autofocus data-ng-model="FileDescription" />
</div>
<div class="col-md-12">
<button type="submit" class="btn btn--primary">Upload File</button>
<a href="#/FileUpload" class="btn btn--secondary">Cancel</a>
</div>
</form>
发生上述错误的部分是:
<input type="file" name="file" accept="image/*" onchange="angular.element(this).scope().selectFileForUpload(this.files)" class="form-control input-bordered" required>
我的控制器的一部分具有此功能作为范围变量。
$scope.selectFileForUpload = function (files) {
$scope.SelectedFileForUpload = file[0];
}
为避免此错误,我该怎么做?
答案 0 :(得分:0)
̶$̶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];
}
坦率地说,函数名和变量名的区别在于一个字母的大写,这是不好的编程习惯。它使代码易于出错并且难以阅读。
建议不要使用与ng-model controller一起使用的自定义指令,而不要使用angular.element(this).scope()
:
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>
angular.element的.scope()
方法要求启用Debug Data。缩小版本的AngularJS并非如此。
此外,用onchange
属性调用的事件处理程序未与AngularJS执行上下文及其摘要周期集成在一起。只有在AngularJS执行上下文中应用的操作才能受益于AngularJS数据绑定,异常处理,属性监视等。
有关更多信息,请参见ng-model for <input type=“file”/>
(with directive DEMO)