我是角的新手。我试图从HTML“文件”字段读取上传的文件路径,每当“更改”发生在这个字段上。如果我使用“onChange”,它可以工作,但当我以angular的方式使用“ng-change”时,它就不起作用了。
<script>
var DemoModule = angular.module("Demo",[]);
DemoModule .controller("form-cntlr",function($scope){
$scope.selectFile = function()
{
$("#file").click();
}
$scope.fileNameChaged = function()
{
alert("select file");
}
});
</script>
<div ng-controller="form-cntlr">
<form>
<button ng-click="selectFile()">Upload Your File</button>
<input type="file" style="display:none"
id="file" name='file' ng-Change="fileNameChaged()"/>
</form>
</div>
fileNameChaged()从不调用。Firebug也不会显示任何错误。
没有文件上传控件的绑定支持
https://github.com/angular/angular.js/issues/1375
<div ng-controller="form-cntlr">
<form>
<button ng-click="selectFile()">Upload Your File</button>
<input type="file" style="display:none"
id="file" name='file' onchange="angular.element(this).scope().fileNameChanged(this)" />
</form>
</div>
而不是
<input type="file" style="display:none"
id="file" name='file' ng-Change="fileNameChanged()" />
你能试试吗?
<input type="file" style="display:none"
id="file" name='file' onchange="angular.element(this).scope().fileNameChanged()" />
注意:这要求angular应用程序始终处于调试模式。如果调试模式被禁用,这将在产品代码中不起作用。
在函数中变化
而不是
$scope.fileNameChanged = function() {
alert("select file");
}
你能试试吗?
$scope.fileNameChanged = function() {
console.log("select file");
}
下面是一个文件上传的工作示例,拖放文件上传可能会有帮助
http://jsfiddle.net/danielzen/utp7j/
Angular文件上传信息
在ASP中上传AngularJS文件的URL。网
https://github.com/geersch/AngularJSFileUpload
AngularJs原生多文件上传与NodeJS的进展
http://jasonturim.wordpress.com/2013/09/12/angularjs-native-multi-file-upload-with-progress/
ngUpload - AngularJS中使用iframe上传文件的服务
http://ngmodules.org/modules/ngUpload
我做了一个小指令来监听文件输入的变化。
View JSFiddle
view.html:
<input type="file" custom-on-change="uploadFile">
controller.js:
app.controller('myCtrl', function($scope){
$scope.uploadFile = function(event){
var files = event.target.files;
};
});
directive.js:
app.directive('customOnChange', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var onChangeHandler = scope.$eval(attrs.customOnChange);
element.on('change', onChangeHandler);
element.on('$destroy', function() {
element.off();
});
}
};
});
我扩展了@Stuart Axon的想法,为文件输入添加双向绑定(即允许通过将模型值重置为null来重置输入):
app.directive('bindFile', [function () {
return {
require: "ngModel",
restrict: 'A',
link: function ($scope, el, attrs, ngModel) {
el.bind('change', function (event) {
ngModel.$setViewValue(event.target.files[0]);
$scope.$apply();
});
$scope.$watch(function () {
return ngModel.$viewValue;
}, function (value) {
if (!value) {
el.val("");
}
});
}
};
}]);
Demo