Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've built a simple AngularJS directive to implement Dropzone.js on elements. I'd like to display uploaded files using an ng-repeat outside of the directive, but I can't make it work since the 'addedfile' callback of the element seems to be creating a copy of the array (scope.files). The callback can read the array (or the copy of the array) but when I push a new element on it doesn't affect the ng-repeat. How can I make it work ?

.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
                    });
                }
            })
        }
    }
});
share|improve this question

2 Answers 2

up vote 5 down vote accepted

As this happends outside the realm of Angular you have to notify Angular of the change by wrapping it in an $apply:

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

If you need drop files functionality in angular you can use this lightweight directive: 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);
      }); 
    }
  }
}];
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.