本文实例为大家分享了angularjs上传多张图片并预览的具体代码,供大家参考,具体内容如下
directive.js
angular.module('routerModule').directive('fileModel',['$parse','fileReader',function($parse,fileReader) {
return {
restrict:'A',link:function(scope,element,attrs,ngModel) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
var imgviewID = attrs["imgViewId"];
var imgView = angular.element(document.querySelector("."+imgviewID));
element.bind('change',function(event) {
scope.$apply(function() {
modelSetter(scope,element[0].files[0]);
});
//附件预览
scope.file = (event.srcElement || event.target).files[0];
fileReader.readAsDataUrl(scope.file,scope).then(function(result) {
imgView.attr("src",result);
});
});
}
}
}]);
angular.module('routerModule').factory('fileReader',["$q","$log",function($q,$log) {
var onLoad = function(reader,deferred,scope) {
return function() {
scope.$apply(function() {
deferred.resolve(reader.result);
});
}
}
var onError = function(reader,scope) {
return function() {
scope.$apply(function() {
deferred.reject(reader.result);
});
};
};
var getReader = function(deferred,scope) {
var reader = new FileReader();
reader.onload = onLoad(reader,scope);
reader.onerror = onError(reader,scope);
return reader;
};
var readAsDataURL = function(file,scope) {
var deferred = $q.defer();
var reader = getReader(deferred,scope);
reader.readAsDataURL(file);
return deferred.promise;
}
return {
readAsDataUrl: readAsDataURL
};
}
]);
html关键代码