總體邏輯:service提供FileReader函數,directive提供點擊事件的綁定和監聽,controller用來修改html上的ng-src屬性值html
1.HTMLpromise
<input type="file" file-model="myFile">/*AngularJS定義的file-Model屬性用於對文件進行操做*/ <img alt="配圖預覽" ng-src="{{imageSrc}}">/*這裏用來放置上傳的圖片進行預覽,ng-src是AngularJS定義替代<img>標籤的src屬性,其值將在後臺邏輯得到*/
2.AngularJSapp
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)Directivethis
.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)Servicespa
.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 }; });