如何解决TypeError:angular.element(..).scope(..).selectFileForUpl



我正试图使用angularjs在asp.net mvc中上传一个文件。我有以下作为我的文件上传UI。

<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];
}

我应该采取哪些不同的措施来避免这个错误?

̶$̶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型号控制器一起工作的自定义指令:

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元素的.scope()方法需要启用调试数据。AngularJS的缩小版本并非如此。

此外,使用onchange属性调用的事件处理程序未与AngularJS执行上下文及其摘要周期集成。只有在AngularJS执行上下文中应用的操作才会受益于AngularJS数据绑定、异常处理、属性监视等。

有关更多信息,请参阅<input type=“file”/>(带指令DEMO(的ng模型

最新更新