3

我构建了一个简单的 AngularJS 指令来在元素上实现 Dropzone.js。我想在指令之外使用 ng-repeat 显示上传的文件,但我无法使其工作,因为元素的“addfile”回调似乎正在创建数组的副本(scope.files)。回调可以读取数组(或数组的副本),但是当我在其上推送新元素时不会影响 ng-repeat。我怎样才能使它工作?

.directive('dropzone', function() {
    return {
        restrict: 'EA',
        link: function(scope, el, attrs) {

            el.dropzone({
                url: attrs.url,
                maxFilesize: attrs.maxsize,
                init: function() {
                    scope.files.push({file: 'added'}); // here works
                    this.on('success', function(file, json) {
                    });
                    this.on('addedfile', function(file) {
                        scope.files.push({file: 'added'}); // here doesn't work
                    });
                }
            })
        }
    }
});
4

3 回答 3

5

由于这发生在 Angular 领域之外,您必须通过将更改包装在 $apply 中来通知 Angular:

this.on('addedfile', function(file) {
  scope.$apply(function(){
    scope.files.push({file: 'added'});
  });
});
于 2013-05-31T11:26:24.013 回答
0

如果您需要 Angular 中的拖放文件功能,您可以使用这个轻量级指令: angular-file-upload

<div ng-controller="MyCtrl">
  <input type="file" ng-file-select="onFileSelect($files)" multiple>
  <div class="drop-box" ng-file-drop="onFileSelect($files);">drop files here</div>

JS:

//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var $file = $files[i];
      $upload.upload({
        url: 'my/upload/url',
        file: $file,
        progress: function(e){}
      }).then(function(data, status, headers, config) {
        // file is uploaded successfully
        console.log(data);
      }); 
    }
  }
}];
于 2013-10-28T22:25:52.067 回答
-1

功能dropZone(){

return function (scope, element, attrs) {
    //scope.files="esto contiene files";
    console.log(scope);


    element.dropzone({
        url: "upload.php",
        maxFilesize: 100,
        paramName: "uploadfile",
        maxThumbnailFilesize: 5,
        init: function () {
            scope.files.push({file: 'added'});
            this.on('success', function (file, json) {
            });
            this.on('addedfile', function (file) {
                scope.$apply(function () {
                    alert(file);
                    scope.files.push({file: 'added'});
                });
            });
            this.on('drop', function (file) {
                alert('file');
            });
        }
    });

}

}

于 2017-10-20T16:58:01.480 回答