Question

I'm trying to create a directive that watches for a file being dragged onto an element. My issue is that I can't seem to trigger the watch on scope.files I've also tried creating an isolated scope:

scope:{files:'='} 

and then doing

scope.$watch('files',function(){})

inside the link function, but no luck.

How do I get this watch to pick up on the files being updated?

I have added "scope.files = []" because it was null initially when watch was being set up.

angular.module('myApp').directive('dragDrop', [function () {
return {

    link: function (scope, element, attrs) {
        scope.files = [];
        scope.$watch(scope.files, function () {
            if (scope.files !== undefined && scope.files.length === 1) alert("a file has been dropped");
        });
        element.on('dragenter', function (e) {
            e.stopPropagation();
            e.preventDefault();
            $(this).css('border', '2px solid #0B85A1');
        });
        element.on('dragover', function (e) {
            e.stopPropagation();
            e.preventDefault();
        });
        element.on('drop', function (e) {

            $(this).css('border', '0px');
            e.preventDefault();
            //var files = e.originalEvent.dataTransfer.files;
            scope.files = e.originalEvent.dataTransfer.files;

        });
    }
};
Was it helpful?

Solution

you should set third parameter of $watch() as true,

scope.$watch('files',function(){},true)

here is a nice article about $watch() vs. $watchCollection()

UPDATE

you cannot trigger watch there because you are using primitive object there here is usage of complex object within directive...

PLUNKER

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top