观察在继承范围上创建的对象

时间:2014-03-24 16:43:58

标签: angularjs scope directive watch

我试图创建一个指令来监视正在拖动到元素上的文件。 我的问题是我似乎无法在scope.files上触发监视 我也试过创建一个孤立的范围:

scope:{files:'='} 

然后做

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

里面的链接功能,但没有运气。

如何让这款手表获取正在更新的文件?

我添加了" scope.files = []"因为最初设置手表时它是空的。

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;

        });
    }
};

1 个答案:

答案 0 :(得分:1)

您应将$watch()的第三个参数设置为true

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

这是一篇关于$watch() vs. $watchCollection()

的好文章

<强>更新

你不能在那里触发观察,因为你在那里使用原始对象这里是指令中复杂对象的使用......

PLUNKER

相关问题