【发布时间】:2014-07-16 15:58:58
【问题描述】:
我正在尝试使用 AngularJS 编写一个文件读取器指令,该指令将接收图像,然后将它们的 URL 推送到一个数组中,这样我就可以遍历该数组并将图像绘制到 DOM。
但是,我似乎无法从上传的图像中获取所需的 URL,以便在图像源标签中调用它。这是我正在处理的:
fileReader 指令
app.directive('fileReader', ['$rootScope', function($rootScope) {
return {
restrict: 'E',
scope: true,
templateUrl:'views/templates/file-reader.html',
link: function (scope, element, attributes, controller) {
element.bind("change", function(event) {
var files = event.target.files;
var reader = new FileReader();
reader.onload = function() {
$rootScope.imageInfo = this.result;
$rootScope.$digest(); //digest is required to run with watch?
console.log("caught a change");
};
reader.readAsDataURL(files[0]);
});
},
controller: 'UploadController'
}
}]);
上传控制器
controllers.controller('UploadController', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.imageUrls = []; //array of URL
$rootScope.$watch('imageInfo', function() {
if ($rootScope.imageInfo) { //if something has been loaded
console.log("Inside the rootScope watch function");
$scope.imageUrls.push($rootScope.imageInfo); //add the URL to the array
}
$scope.printArray();//to check if the array worked
});
$scope.printArray = function(){
console.log("this is the image URL array:");
for(var i=0; i<$scope.imageUrls.length; i++){
console.log($scope.imageUrls[i]);
};
console.log("end image url");
};
}]);
file-reader.html:<input type='file' id="files" name="files[]">
所以最初,我在 onload 块之外有我的reader.readAsDataURL(file[0]) 行,但它没有传递我通过阅读器提取的 URL。
然而,这种方式 $watch 甚至没有被激活。为什么不呢?
如何使用它来帮助将上传的图片 URL 传递到数组中?
(这都是客户端。我意识到我实际上并没有“上传”任何超出 DOM 的内容。)
更新:
我已经通过简单地调用 $digest 解决了 $watch 不被调用的问题,但我仍然无法获取数据的 URL 来创建图像,而不是像:data:image/gif;base64,R0lGODlh9QC0AOZ0AAwKClNNSpeWloeGhvTXozAqKbe2t0osEMm4r…1pGcsCIoJgiyf8+HPbIGY+OCEjIGhIBw8g8GDcnHgVKnCVCm7BAIooctEhiymDoBHBF4EAADs=
我重新排列了一些术语,并在指令中更新了上面的代码。
【问题讨论】:
标签: javascript angularjs file-upload filereader watch