angular ng-upload-file $ watch not working

时间:2015-07-29 13:42:43

标签: javascript jquery html angularjs ng-file-upload

我有以下代码。

HTML:

<div class="button" ngf-select ng-model="files">Upload using model $watch</div>
<img width="80" height="80" ngf-src="files[0]" ngf-default-src="'/thumb.jpg'" ngf-accept="'image/*'">

JAVASCRIPT:

$scope.$watch('[files]', function () {
        $scope.upload($scope.files);
        console.log($scope.files);
    });

    $scope.log = '';

    $scope.upload = function (files) {
        if (files && files.length) {
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                Upload.upload({
                    url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
                    fields: {
                        'username': $scope.username
                    },
                    file: file
                }).progress(function (evt) {
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    $scope.log = 'progress: ' + progressPercentage + '% ' +
                                evt.config.file.name + '\n' + $scope.log;
                }).success(function (data, status, headers, config) {
                    $timeout(function() {
                        $scope.log = 'file: ' + config.file.name + ', Response: ' + JSON.stringify(data) + '\n' + $scope.log;
                    });
                });
            }
        }
    };

上面的代码在jsFiddle中运行正常,我也仔细地遵循了这个documentation。当我在img width="80" height="80" ngf-src="files[0]" ngf-default-src="'/thumb.jpg'" ngf-accept="'image/*'">上显示的窗口浏览器上选择一个图像时,我得到了它。到现在为止还挺好。

$scope.$watch似乎仅适用于onload和console.log($scope.files);打印undefined,第二次该角度应调用摘要循环时它不会调用$scope.$watch来阻止它拨打将要执行上传的$scope.upload($scope.files);。没有任何事情发生,好像ng-model="files"不起作用。我花了几个小时调试这个请帮忙。

0 个答案:

没有答案