当模型在范围内更新时,$ watch不起作用.$ apply in directive

Abd*_*eez 17 javascript watch angularjs

我有一个指令,我在指令范围的'existingfiles'模型上添加了一个监视.当模型通过范围发生变化时.$ apply,监视器中没有调用监听器.

这是指令代码,请告诉我,如果我在这里遗漏了一些东西,

   directive('fileuploadPlugin', function() {
    var linkFn;
    linkFn = function(scope, element, attrs) {
        angular.element(element).ready(function() {
            jQuery('#fileupload').fileupload({
                done: function (e, data) {
                    scope.$apply(function(scope) {
                        for(var i=0; i < data.result.filesuploaded.length; i++){
                                      scope.existingfiles.push(data.result.filesuploaded[i]);
                    };                              
                    });
                }
        });
        scope.$watch('existingfiles', function(newValue, oldValue) {
                element.imagesLoaded(function() {
                scope.$apply( function() {
                    element.masonry({
                        itemSelector : '.box'
                    });
                });
            });
        });
    };
    return {
        templateUrl : 'templates/fileupload_plugin.htm',
        restrict    : 'A',
        scope       : {
            existingfiles   : '=ngModel',
        },
        link        : linkFn
    };  
     })
Run Code Online (Sandbox Code Playgroud)

这是我对指令的呼吁,

<div fileupload-plugin ng-model="existingfiles"></div>
Run Code Online (Sandbox Code Playgroud)

请告诉我如何确保正确观看模型

Abd*_*eez 40

通过将'true'作为$ watch调用的第三个参数来解决问题.请在这里找到关于第三个参数的更多信息,

$ rootScope上的Angular Docs

  • 或者记得在每次更改范围后调用范围.$ digest()以强制在控制器中更新 (6认同)