邏輯理清楚了:service提供FileReader函數,directive提供點擊事件的綁定和監聽,controller用來修改html上的ng-src屬性值
1.HTML
<input type="file" file-model="myFile">/*AngularJS定義的file-Model屬性用於對文件進行操作*/ <img alt="配圖預覽" ng-src="{{imageSrc}}">/*這里用來放置上傳的圖片進行預覽,ng-src是AngularJS定義替代<img>標簽的src屬性,其值將在后台邏輯獲得*/
2.AngularJS
1)Controller
.controller('AddarticleCtrl', function ($scope,fileReader) {/*Controller是實際操作html元素的部分*/
$scope.getFile= function () {
fileReader.readAsDataUrl($scope.myFile,$scope)/*注意這里$scope.myFile,要看實際情況,調試發現這里用該調用入參數的myFile屬性*/
.then(function (result) {
$scope.imageSrc=result;
});
};
});
2)Directive
.directive('fileModel', function ($parse) {/*$parse是AngularJS的內置directive*/
return {
restrict: 'A',/*限制該directive的聲明方式 為Attribute*/
link: function (scope, element, attrs) {
var model=$parse(attrs.fileModel);
var modelSetter=model.assign;
element.bind('change',function (event) {/*頁面加載時執行*/
scope.$apply(function () {/*當用戶點擊html上的input標簽,選中需要上傳的圖片 然后點擊確定后執行*/
modelSetter(scope,element[0].files[0]);
});
scope.getFile();
});
}
};
});
3)Service
.service('fileReader', function ($q) {
// AngularJS will instantiate a singleton by calling "new" on this function
var onLoad=function (reader,deferred,scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
var onError=function (reader,deferred,scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
var getReader=function (deferred,scope) {
var reader=new FileReader();
reader.onload=onLoad(reader,deferred,scope);
reader.onerror=onError(reader,deferred,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
};
});
