【发布时间】:2015-07-02 01:20:14
【问题描述】:
我想使用 AngularJs 上传带有 HTML5 输入类型=“文件”的文件/图像,并且当用户上传图像时显示预览。所以我以这种方式创建了我的自定义指令:
var modulo = angular.module('myApp', []);
modulo.directive('fileModel', function () {
return {
restrict: 'AEC',
link: function(scope, element, attrs) {
element.bind('change', function (event) {
//Take the object
var fetchFile = event.target.files[0];
//emit the object upward
scope.$emit('fileSelected', fetchFile);
});
}
};
});
现在我在获取对象(文件/图像)时显示我的控制器,并且我想使用这个控制器显示预览。
modulo.controller('myController', function ($scope, $http) {
var files;
$scope.$on('fileSelected', function(event, fetchFile) {
//Receive the object from another scope with emit
files = fetchFile;
var reader = new FileReader();
reader.onloadend = function () {
//Put the object/image in page html with scope
$scope.content = reader.fetchFile;
};
});
});
最后我展示了我的 html 页面,我希望在输入文件中显示预览。
<html ng-app="myApp">
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/libs/angular.js/angular.js"></script>
<script src="script.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Select file</h1>
<input type="file" file-model/>
<img ng-src="{{content}}"/>
<div>
<button ng-click="send()">
send
</button>
</div>
</body>
</html>
通过这种方式,我在这个 sn-p 中也没有获得预览,没有我会做的用 Json 发送图像的功能。我该如何解决这个问题?谢谢!
【问题讨论】:
标签: javascript jquery angularjs file-upload angularjs-directive