如何在angularjs中为readAsDataURL()创建回调?

时间:2017-02-27 10:41:27

标签: javascript angularjs data-uri

//Module
var flasherApp = angular.module('flasherApp', []);

//Service
flasherApp.service('albumService', function ($timeout) {
    this.createDataURL = function (img) {
        return $timeout(function () {
            var reader = new FileReader();
            reader.onload = imageIsLoaded
                reader.readAsDataURL(img);
            function imageIsLoaded(e) {
                return e.target.result;
            };
        }, 100);

    }
});

//Directive
flasherApp.directive('ngImgFiles', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var model = $parse(attrs.ngImgFiles);
                    var modelSetter = model.assign;
                    element.bind('change', function () {
                        scope.$apply(function () {
                            modelSetter(scope, element[0].files);
                        });
                    });
                }
            };
        }
    ]);

//Controller
flasherApp.controller('albumCntrl', ['$scope', 'albumService', function ($scope, albumService) {

            $scope.files = [];
            $scope.imageDataUrls = []

            $scope.rows = function (n) {
                return new Array($scope.imageDataUrls);
            };

            $scope.upload = function () {
                angular.forEach($scope.files, function (file, key) {
                    albumService.createDataURL(file).then(function (imageDataUrl) {
                        alert(imageDataUrl);
                        $scope.imageDataUrls.push(imageDataUrl);
                    });

                });
            }

        }
    ]);

HTML

<input type="file" multiple="multiple" accept="image/JPEG, image/BMP, image/PNG, image/GIF, image/TIFF" id="img-upload" ng-img-files="files" name="file" />
<button data-ng-click="upload()">Upload</button>
<div class="row" data-ng-repeat="row in rows track by $index">
   <div class="col-sm-3" data-ng-repeat="imageDataUrl in imageDataUrls | limitTo:($parent.$index*4):((($parent.$index+1)*4)-1)" >
      <img alt="" class="img-responsive" style="width:100%;height:100%" src="  {{imageDataUrl}}"/>
   </div>
</div>

我在createDataURL中调用albumService函数,它包含一个异步函数,但回调没有正确发生

1 个答案:

答案 0 :(得分:1)

您需要从createDataURL()方法返回 Promise 。可以使用$q,之后可以使用.then(sucessCallback, errorCallback)

flasherApp.service('albumService', function ($timeout, $q) {
    this.createDataURL = function (img) {
        var deferred = $q.defer();
        $timeout(function () {
            var reader = new FileReader();
            reader.onload = function (e) {
                deferred.resolve(e.target.result)
            }
            reader.onerror = function (e) {
                deferred.reject()
            }
            reader.readAsDataURL(img);
        }, 100);
        return deferred.promise;
    }
});