Javascript 通过Angular指令在DOM上上载和显示图像
我正在尝试使用AngularJS编写一个文件读取器指令,该指令将接收图像,然后将它们的URL推送到一个数组中,这样我就可以遍历该数组并将图像绘制到DOM中 然而,我似乎无法从上传的图像中获取所需的URL,以便在图像源标记中调用它。以下是我正在处理的问题: 文件阅读器指令Javascript 通过Angular指令在DOM上上载和显示图像,javascript,angularjs,file-upload,filereader,watch,Javascript,Angularjs,File Upload,Filereader,Watch,我正在尝试使用AngularJS编写一个文件读取器指令,该指令将接收图像,然后将它们的URL推送到一个数组中,这样我就可以遍历该数组并将图像绘制到DOM中 然而,我似乎无法从上传的图像中获取所需的URL,以便在图像源标记中调用它。以下是我正在处理的问题: 文件阅读器指令 app.directive('fileReader', ['$rootScope', function($rootScope) { return { restrict: 'E', scop
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");
};
}]);
controllers.controller('UploadController',['$scope','$rootScope',函数($scope,$rootScope){
$scope.imageUrls=[];//URL数组
$rootScope.$watch('imageInfo',function(){
if($rootScope.imageInfo){//如果加载了某些内容
log(“在rootScope监视函数中”);
$scope.imageUrls.push($rootScope.imageInfo);//将URL添加到数组中
}
$scope.printary();//检查数组是否工作
});
$scope.printary=函数(){
log(“这是图像URL数组:”);
对于(var i=0;i您是否尝试过在$watch函数中将objectEquality设置为true,如下所示:
$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
}, true); // add true here
这还会侦听嵌套值中的更改
这里还有一篇我发现的小文章/博客文章,提供了不同$watch机制的良好分类和性能。在决定使用哪个$watch函数时可能会很有用:
谢谢你的文章。不过,我通过调用$digest解决了$watch的问题——现在我仍然无法获取图像URL(这不是一个角度上的问题,)你能帮我解决这个问题吗?请看我上面的编辑。谢谢!这是图像url为空的情况吗?调用$watch后数组中保存了什么?有很多事情;主要是我没有意识到event.target.files是一个数组,需要在末尾添加[0]。但我已经解决了。谢谢。(: