【发布时间】:2015-06-29 21:07:03
【问题描述】:
我想用 AngularJs 上传一个文件(所以图像)...我读到 AngularJs 不支持标签输入类型 =“文件”所以我读到我需要自定义指令...我想获取输入文件并将其用于在同一页面 html 上显示预览(缩略图),并在控制器中将文件上传到服务器...在我的页面 html 中,我编写了以下代码:
<body ng-controller="myController">
<h1>Select file</h1>
<input type="file" file-model="myFile" />
<div>
<h2>File content is:</h2>
<pre>{{ content }}</pre>
</div>
</body>
我写了这个指令:
var modulo = angular.module('myApp', []);
modulo.directive('fileModel', function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('change', function (event) {
var file = event.target.files[0];
scope.$emit("fileSelected", file);
});
}
};
});
这是我的控制器:
modulo.controller('myController', function ($scope) {
$scope.$on('fileSelected', function (event, args) {
$scope.content(args.file);
console.log(args.file);
});
});
此代码不起作用...有解决方案吗?哪里出错了?
【问题讨论】:
-
从您发布的代码中,它似乎缺少 ng-app 声明 - 将 ng-app 放在 body 标记上,如下所示:
-
我在这个例子中省略了,因为它被提供了
标签: javascript jquery angularjs file-upload angularjs-directive