Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropzone.js callback access Angular scope

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
                    });
                }
            })
        }
    }
});
like image 823
Antonio Madonna Avatar asked Nov 18 '25 00:11

Antonio Madonna


1 Answers

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'});
  });
});
like image 168
joakimbl Avatar answered Nov 19 '25 13:11

joakimbl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!