js回调访问Angular作用域

Dropzone.js callback access Angular scope

本文关键字:作用域 Angular 访问 回调 js      更新时间:2023-09-26

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

由于这种情况发生在Angular之外,你必须通过将其封装在$apply:

中来通知Angular。
this.on('addedfile', function(file) {
  scope.$apply(function(){
    scope.files.push({file: 'added'});
  });
});

如果你需要在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);
      }); 
    }
  }
}];

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

}