【发布时间】:2015-07-05 08:30:00
【问题描述】:
我正在尝试预览从多个输入类型文件中选择的图像。为此,我想要文件路径列表并使用这些路径来预览图像。
但这里我在img标签中使用了ng-src,这些路径设置在ng-src上,而且我想根据使用ng-repeat的文件选择创建img标签。
假设我将在 input type=file 上选择 5 个文件,然后创建 5 个 img 标记。假设我将文件从 5 更改为 2,然后删除所有 5 个 img 标签并创建 2 个 img 标签。
我不知道ng-repeat 是否是根据文件选择创建img 标签的正确选项?
下面是我的 myfileupload 指令
App.directive('myFileUpload', function (fileService) {
return {link: function (scope, element, attrs) {
element.bind('change', function () {
var index;
var index_file = 0;
for (index = 0; index < element[0].files.length; index++) {
var file=element[0].files[index];
fileService.setFile(element[0].files[index], index_file, attrs.myFileUpload);
index_file++;
var src={};
/*src["src"]=element[0].files[index];*/
fileService.setFilePath(element[0].files[index], index_file, attrs.myFileUpload);
console.log(pathss);
path.push(src);
}
index_file = 0;
});
}
};
});
这是我的服务
App.service('fileService', function () {
var fileService = {};
fileService.getFile = function (name) {
return file[name];
};
fileService.setFile = function (newFile, index, name) {
if (index === 0 && file[name] === undefined)
/*file[name] = [];*/
console.log(file);
file[name][index] = newFile;
/*console.log(name);*/
};
fileService.getFilePath = function (name) {
return filepath[name];
};
fileService.setFilePath = function (newFile, index, name) {
if (index === 0 && file[name] === undefined)
/*file[name] = [];*/
console.log(file);
filepath[name][index] = newFile.val;
/*console.log(name);*/
};
return fileService;
})
我如何创建输入类型文件的控制器
$scope.add=function(){
var name="descimg["+currentg1+"]";
var pathname="imgfile["+currentg1+"]";
file[name] = [];
var $div = angular.element("<div><label id='desccodeL["+currentg1+"]' for='desccodeL["+currentg1+"]''>Code "+currentg1+"</label><textarea rows='3' cols='6' id='desccode["+currentg1+"]' name='desccode["+currentg1+"]' ng-model='blog.desccode["+currentg1+"]''></textarea></div><div><label id='descimgL["+currentg1+"]' for='descimgL["+currentg1+"]'>Image "+currentg1+"</label><input type='file' id='descimg["+currentg1+"]' class='file' name='descimg["+currentg1+"]' my-file-upload='descimg["+currentg1+"]' multiple/></div>");
var e=document.getElementById("outerdiv");
var $div2=angular.element("<div ng repeat='path in "+fileService.getFilePath("descimg["+currentg1+"]"); +"'><img ng-src=''/></div></div >);
var e2=document.getElementById("displayblog");
angular.element(e).append($div).injector().invoke(function($compile) {
var scope = angular.element($div).scope();
$compile($div)(scope);
});
angular.element(e2).append($div2).injector().invoke(function($compile) {
var scope = angular.element($div2).scope();
$compile($div2)(scope);
});
currentg1++;
};
文件元素是在调用 add 函数后动态创建的,当我设置 myservice.setFilePath 时,它在 newFile.val 中给出错误!!!
【问题讨论】:
-
你能贴一些代码吗?听起来您在正确的轨道上,但查看您的模板和控制器将有助于确保。
-
@jordajm 我正在更改我的帖子并包含一些我使用过的代码。我认为它可以帮助您理解我的问题。
标签: angularjs