Dropzone.js回调访问角度范围

时间:2013-05-31 11:23:04

标签: javascript angularjs dropzone.js

我已经构建了一个简单的AngularJS指令来在元素上实现Dropzone.js。 我想在指令之外使用ng-repeat显示上传的文件,但我不能使它工作,因为元素的'addedfile'回调似乎是在创建数组的副本(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
                    });
                }
            })
        }
    }
});

3 个答案:

答案 0 :(得分:5)

因为这发生在Angular的范围之外,你必须通过将它包装在$ apply中来通知Angular:

this.on('addedfile', function(file) {
  scope.$apply(function(){
    scope.files.push({file: 'added'});
  });
});

答案 1 :(得分:0)

如果您需要角度中的drop files功能,可以使用此轻量级指令: 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);
      }); 
    }
  }
}];

答案 2 :(得分:-1)

function 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');
            });
        }
    });

}

}